Sample code for 30+ languages & platforms
PHP ActiveX Requires Chilkat v11.6.0+

Amazon EC2: Find Instances by Tag and State

See more Amazon EC2 Examples

Find running instances whose Name tag matches the supplied value. Parses the two-level reservationSet/instancesSet structure, IDs, addresses, and tags. Different filters are combined with AND; multiple values within one filter are alternatives. Names can match multiple instances. Missing public-address fields are normal for private instances.

Follows nextToken even after an empty page. Tokens are opaque strings; replace the previous NextToken rather than adding duplicates. A repeated token or the 1000-page demonstration bound reports incomplete results. Pages are not an atomic snapshot, and response order is not guaranteed.

Uses the current EC2 Query API (Version=2016-11-15) over HTTPS. Chilkat.Rest and AuthAws sign the GET request with AWS Signature Version 4, service ec2. Set the region once; the code builds the corresponding commercial AWS endpoint. Other partitions require their own endpoint suffix. EC2 returns XML, unlike DynamoDB's JSON protocol. AddQueryParam encodes parameter values.

Load current IAM credentials from a private qa_data/aws/ec2.json with string fields access_key, secret_key, and, for temporary credentials, session_token. Prefer short-lived role credentials. The example explicitly reads this file; it does not discover profiles or refresh expired credentials. The session token is included in the signed query, so keep URLs and diagnostics private. A Socket enables TLS certificate verification before handing its connection to Rest.

IAM permissions for the illustrated requests: ec2:DescribeInstances. Use least-privilege permissions for the intended resources; EC2 describe operations generally require Resource *.

Transport completion, HTTP status, and XML validity are checked separately. API errors contain Errors/Error/Code and RequestID; successful responses use requestId. Check the error code rather than assuming every HTTP 4xx means bad input. Use bounded exponential backoff with jitter for retryable failures. EC2 is eventually consistent: a recent resource change may not appear immediately. Verify account, region, ID, and observed state before retrying a change whose outcome is uncertain.

DescribeInstances reference

Chilkat PHP ActiveX Downloads

PHP ActiveX
<?php

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
$success = 0;
//  Private configuration, not a file in public web content or source control.
//  Load current IAM credentials authorized for the EC2 operation.
$credentials = new COM("Chilkat.JsonObject");
$credentials->Strict = 1;
$success = $credentials->LoadFile('qa_data/aws/ec2.json');
if ($success != 1) {
    print 'Could not load private AWS credentials.' . "\n";
    exit;
}

if (($credentials->JsonTypeOf('access_key') != 1) or ($credentials->stringOf('access_key') == '')) {
    print 'Missing or invalid access_key.' . "\n";
    exit;
}

if (($credentials->JsonTypeOf('secret_key') != 1) or ($credentials->stringOf('secret_key') == '')) {
    print 'Missing or invalid secret_key.' . "\n";
    exit;
}

//  Set this once to the region containing the instances.
$region = 'us-west-2';
$endpoint = new COM("Chilkat.StringBuilder");
$endpoint->Append('ec2.');
$endpoint->Append($region);
$endpoint->Append('.amazonaws.com');
$aws = new COM("Chilkat.AuthAws");
$aws->AccessKey = $credentials->stringOf('access_key');
$aws->SecretKey = $credentials->stringOf('secret_key');
$aws->Region = $region;
$aws->ServiceName = 'ec2';
$aws->SignatureVersion = 4;
$rest = new COM("Chilkat.Rest");
$rest->ConnectTimeoutMs = 20000;
$rest->IdleTimeoutMs = 60000;
$success = $rest->SetAuthAws($aws);
if ($success != 1) {
    print 'Could not configure AWS signing.' . "\n";
    exit;
}

//  Temporary IAM/STS credentials require their session token on every signed request.
//  AddQueryParam includes it in SigV4's canonical query. Never log the request URL.
//  Leave session_token absent or empty only for credentials that do not have one.
if ($credentials->HasMember('session_token') == 1) {
    if ($credentials->JsonTypeOf('session_token') != 1) {
        print 'session_token must be a string.' . "\n";
        exit;
    }

    if ($credentials->stringOf('session_token') != '') {
        $success = $rest->AddQueryParam('X-Amz-Security-Token',$credentials->stringOf('session_token'));
        if ($success != 1) {
            print 'Could not set the session-token parameter.' . "\n";
            exit;
        }

    }

}

//  Supply a Socket to explicitly enable TLS certificate verification.
$connection = new COM("Chilkat.Socket");
$connection->RequireSslCertVerify = 1;
$connection->MaxReadIdleMs = 60000;
$connection->MaxSendIdleMs = 60000;
$success = $connection->Connect($endpoint->getAsString(),443,1,20000);
if ($success != 1) {
    print 'TLS connection failed; inspect diagnostics privately.' . "\n";
    exit;
}

$success = $rest->UseConnection($connection,1);
if ($success != 1) {
    print 'Could not attach the TLS connection.' . "\n";
    exit;
}

//  EC2 uses the Query API and XML responses, not AWS JSON protocol headers.
//  AddQueryParam URL-encodes the values; do not pre-encode IDs or tokens.
$xml = new COM("Chilkat.Xml");
$xml->Strict = 1;
$success = $rest->AddQueryParam('Version','2016-11-15');
if ($success != 1) {
    print 'Could not set Version.' . "\n";
    exit;
}

$responseXml = '';
$errorCode = '';
$instanceName = 'example-instance';
$i = 0;
$j = 0;
$k = 0;
$success = $rest->AddQueryParam('Action','DescribeInstances');
if ($success != 1) {
    print 'Could not set Action.' . "\n";
    exit;
}

$success = $rest->AddQueryParam('Filter.1.Name','tag:Name');
if ($success != 1) {
    print 'Could not set Filter.1.Name.' . "\n";
    exit;
}

$success = $rest->AddQueryParam('Filter.1.Value.1',$instanceName);
if ($success != 1) {
    print 'Could not set Filter.1.Value.1.' . "\n";
    exit;
}

$success = $rest->AddQueryParam('Filter.2.Name','instance-state-name');
if ($success != 1) {
    print 'Could not set Filter.2.Name.' . "\n";
    exit;
}

$success = $rest->AddQueryParam('Filter.2.Value.1','running');
if ($success != 1) {
    print 'Could not set Filter.2.Value.1.' . "\n";
    exit;
}

//  Filters are ANDed. Remove a filter deliberately to broaden the search.
//  Name tags are not unique: process every returned instance, not just the first.
$success = $rest->AddQueryParam('MaxResults','100');
if ($success != 1) {
    print 'Could not set MaxResults.' . "\n";
    exit;
}

$seenTokens = new COM("Chilkat.Hashtable");
$nextToken = '';
$more = 1;
$page = 0;
while (($more == 1)) {
    if ($page == 1000) {
        print 'Page limit reached; enumeration is incomplete. Retain nextToken privately to resume.' . "\n";
        exit;
    }

    $responseXml = $rest->fullRequestNoBody('GET','/');
    if ($rest->LastMethodSuccess != 1) {
        print 'Request did not complete; inspect diagnostics privately.' . "\n";
        exit;
    }

    $success = $xml->LoadXml($responseXml);
    if ($rest->ResponseStatusCode != 200) {
        print 'EC2 HTTP status: ' . $rest->ResponseStatusCode . "\n";
        if ($success == 1) {
            if ($xml->HasChildWithTag('Errors|Error|Code') == 1) {
                $errorCode = $xml->getChildContent('Errors|Error|Code');
                print 'AWS error code: ' . $errorCode . "\n";
            }

            if ($xml->HasChildWithTag('RequestID') == 1) {
                print 'AWS request ID: ' . $xml->getChildContent('RequestID') . "\n";
            }

        }

        //  Keep full error messages and signed request diagnostics private.
        //  UnauthorizedOperation is not a successful dry run. Check IAM permissions.
        //  Retry throttled reads with bounded backoff; renew expired credentials.
        exit;
    }

    if ($success != 1) {
        print 'Expected a well-formed XML response.' . "\n";
        exit;
    }

    if ($xml->Tag != 'DescribeInstancesResponse') {
        print 'Unexpected EC2 response element.' . "\n";
        exit;
    }

    if (($xml->HasChildWithTag('requestId') != 1) or ($xml->getChildContent('requestId') == '')) {
        print 'Missing or empty requestId.' . "\n";
        exit;
    }

    print 'AWS request ID: ' . $xml->getChildContent('requestId') . "\n";
    if ($xml->HasChildWithTag('reservationSet') != 1) {
        print 'Expected reservationSet.' . "\n";
        exit;
    }

    $i = 0;
    while (($i < $xml->NumChildrenAt('reservationSet'))) {
        $xml->I = $i;
        $j = 0;
        while (($j < $xml->NumChildrenAt('reservationSet|item[i]|instancesSet'))) {
            $xml->J = $j;
            if (($xml->HasChildWithTag('reservationSet|item[i]|instancesSet|item[j]|instanceId') != 1) or ($xml->getChildContent('reservationSet|item[i]|instancesSet|item[j]|instanceId') == '')) {
                print 'Missing or empty reservationSet|item[i]|instancesSet|item[j]|instanceId.' . "\n";
                exit;
            }

            print 'Instance ID: ' . $xml->getChildContent('reservationSet|item[i]|instancesSet|item[j]|instanceId') . "\n";
            if ($xml->HasChildWithTag('reservationSet|item[i]|instancesSet|item[j]|instanceState|name') == 1) {
                print 'State: ' . $xml->getChildContent('reservationSet|item[i]|instancesSet|item[j]|instanceState|name') . "\n";
            }

            if ($xml->HasChildWithTag('reservationSet|item[i]|instancesSet|item[j]|instanceType') == 1) {
                print 'Type: ' . $xml->getChildContent('reservationSet|item[i]|instancesSet|item[j]|instanceType') . "\n";
            }

            if ($xml->HasChildWithTag('reservationSet|item[i]|instancesSet|item[j]|imageId') == 1) {
                print 'AMI: ' . $xml->getChildContent('reservationSet|item[i]|instancesSet|item[j]|imageId') . "\n";
            }

            if ($xml->HasChildWithTag('reservationSet|item[i]|instancesSet|item[j]|privateIpAddress') == 1) {
                print 'Private IPv4: ' . $xml->getChildContent('reservationSet|item[i]|instancesSet|item[j]|privateIpAddress') . "\n";
            }

            if ($xml->HasChildWithTag('reservationSet|item[i]|instancesSet|item[j]|ipAddress') == 1) {
                print 'Public IPv4: ' . $xml->getChildContent('reservationSet|item[i]|instancesSet|item[j]|ipAddress') . "\n";
            }

            if ($xml->HasChildWithTag('reservationSet|item[i]|instancesSet|item[j]|privateDnsName') == 1) {
                print 'Private DNS: ' . $xml->getChildContent('reservationSet|item[i]|instancesSet|item[j]|privateDnsName') . "\n";
            }

            if ($xml->HasChildWithTag('reservationSet|item[i]|instancesSet|item[j]|dnsName') == 1) {
                print 'Public DNS: ' . $xml->getChildContent('reservationSet|item[i]|instancesSet|item[j]|dnsName') . "\n";
            }

            if ($xml->HasChildWithTag('reservationSet|item[i]|instancesSet|item[j]|subnetId') == 1) {
                print 'Subnet: ' . $xml->getChildContent('reservationSet|item[i]|instancesSet|item[j]|subnetId') . "\n";
            }

            if ($xml->HasChildWithTag('reservationSet|item[i]|instancesSet|item[j]|vpcId') == 1) {
                print 'VPC: ' . $xml->getChildContent('reservationSet|item[i]|instancesSet|item[j]|vpcId') . "\n";
            }

            $k = 0;
            while (($k < $xml->NumChildrenAt('reservationSet|item[i]|instancesSet|item[j]|tagSet'))) {
                $xml->K = $k;
                if (($xml->HasChildWithTag('reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key') != 1) or ($xml->getChildContent('reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key') == '')) {
                    print 'Missing or empty reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key.' . "\n";
                    exit;
                }

                print 'Tag key: ' . $xml->getChildContent('reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key') . "\n";
                if ($xml->HasChildWithTag('reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|value') == 1) {
                    print 'Tag value: ' . $xml->getChildContent('reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|value') . "\n";
                }

                $k = $k + 1;
            }

            $j = $j + 1;
        }

        $i = $i + 1;
    }

    $page = $page + 1;
    $more = 0;
    $nextToken = '';
    if ($xml->HasChildWithTag('nextToken') == 1) {
        $nextToken = $xml->getChildContent('nextToken');
    }

    if ($nextToken != '') {
        if ($seenTokens->Contains($nextToken) == 1) {
            print 'Repeated pagination token; enumeration is incomplete.' . "\n";
            exit;
        }

        $success = $seenTokens->AddInt($nextToken,1);
        if ($success != 1) {
            print 'Could not track pages.' . "\n";
            exit;
        }

        if ($page > 1) {
            $success = $rest->RemoveQueryParam('NextToken');
            if ($success != 1) {
                print 'Could not replace pagination token.' . "\n";
                exit;
            }

        }

        $success = $rest->AddQueryParam('NextToken',$nextToken);
        if ($success != 1) {
            print 'Could not set NextToken.' . "\n";
            exit;
        }

        $more = 1;
    }

}

print 'Enumeration complete.' . "\n";

?>