Sample code for 30+ languages & platforms
Visual FoxPro 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 Visual FoxPro Downloads

Visual FoxPro
LOCAL lnSuccess
LOCAL loCredentials
LOCAL lcRegion
LOCAL loEndpoint
LOCAL loAws
LOCAL loRest
LOCAL loConnection
LOCAL loXml
LOCAL lcResponseXml
LOCAL lcErrorCode
LOCAL lcInstanceName
LOCAL i
LOCAL j
LOCAL k
LOCAL loSeenTokens
LOCAL lcNextToken
LOCAL lnMore
LOCAL lnPage

*  Assumes Chilkat is unlocked. See Global Unlock Sample.
lnSuccess = 0
*  Private configuration, not a file in public web content or source control.
*  Load current IAM credentials authorized for the EC2 operation.
loCredentials = CreateObject('Chilkat.JsonObject')
loCredentials.Strict = 1
lnSuccess = loCredentials.LoadFile("qa_data/aws/ec2.json")
IF (lnSuccess <> 1) THEN
    ? "Could not load private AWS credentials."
    RELEASE loCredentials
    CANCEL
ENDIF

IF ((loCredentials.JsonTypeOf("access_key") <> 1) OR (loCredentials.StringOf("access_key") = "")) THEN
    ? "Missing or invalid access_key."
    RELEASE loCredentials
    CANCEL
ENDIF

IF ((loCredentials.JsonTypeOf("secret_key") <> 1) OR (loCredentials.StringOf("secret_key") = "")) THEN
    ? "Missing or invalid secret_key."
    RELEASE loCredentials
    CANCEL
ENDIF

*  Set this once to the region containing the instances.
lcRegion = "us-west-2"
loEndpoint = CreateObject('Chilkat.StringBuilder')
loEndpoint.Append("ec2.")
loEndpoint.Append(lcRegion)
loEndpoint.Append(".amazonaws.com")
loAws = CreateObject('Chilkat.AuthAws')
loAws.AccessKey = loCredentials.StringOf("access_key")
loAws.SecretKey = loCredentials.StringOf("secret_key")
loAws.Region = lcRegion
loAws.ServiceName = "ec2"
loAws.SignatureVersion = 4
loRest = CreateObject('Chilkat.Rest')
loRest.ConnectTimeoutMs = 20000
loRest.IdleTimeoutMs = 60000
lnSuccess = loRest.SetAuthAws(loAws)
IF (lnSuccess <> 1) THEN
    ? "Could not configure AWS signing."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    CANCEL
ENDIF

*  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 (loCredentials.HasMember("session_token") = 1) THEN
    IF (loCredentials.JsonTypeOf("session_token") <> 1) THEN
        ? "session_token must be a string."
        RELEASE loCredentials
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        CANCEL
    ENDIF

    IF (loCredentials.StringOf("session_token") <> "") THEN
        lnSuccess = loRest.AddQueryParam("X-Amz-Security-Token",loCredentials.StringOf("session_token"))
        IF (lnSuccess <> 1) THEN
            ? "Could not set the session-token parameter."
            RELEASE loCredentials
            RELEASE loEndpoint
            RELEASE loAws
            RELEASE loRest
            CANCEL
        ENDIF

    ENDIF

ENDIF

*  Supply a Socket to explicitly enable TLS certificate verification.
loConnection = CreateObject('Chilkat.Socket')
loConnection.RequireSslCertVerify = 1
loConnection.MaxReadIdleMs = 60000
loConnection.MaxSendIdleMs = 60000
lnSuccess = loConnection.Connect(loEndpoint.GetAsString(),443,1,20000)
IF (lnSuccess <> 1) THEN
    ? "TLS connection failed; inspect diagnostics privately."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    CANCEL
ENDIF

lnSuccess = loRest.UseConnection(loConnection,1)
IF (lnSuccess <> 1) THEN
    ? "Could not attach the TLS connection."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    CANCEL
ENDIF

*  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.
loXml = CreateObject('Chilkat.Xml')
loXml.Strict = 1
lnSuccess = loRest.AddQueryParam("Version","2016-11-15")
IF (lnSuccess <> 1) THEN
    ? "Could not set Version."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lcResponseXml = ""
lcErrorCode = ""
lcInstanceName = "example-instance"
i = 0
j = 0
k = 0
lnSuccess = loRest.AddQueryParam("Action","DescribeInstances")
IF (lnSuccess <> 1) THEN
    ? "Could not set Action."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loRest.AddQueryParam("Filter.1.Name","tag:Name")
IF (lnSuccess <> 1) THEN
    ? "Could not set Filter.1.Name."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loRest.AddQueryParam("Filter.1.Value.1",lcInstanceName)
IF (lnSuccess <> 1) THEN
    ? "Could not set Filter.1.Value.1."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loRest.AddQueryParam("Filter.2.Name","instance-state-name")
IF (lnSuccess <> 1) THEN
    ? "Could not set Filter.2.Name."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loRest.AddQueryParam("Filter.2.Value.1","running")
IF (lnSuccess <> 1) THEN
    ? "Could not set Filter.2.Value.1."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

*  Filters are ANDed. Remove a filter deliberately to broaden the search.
*  Name tags are not unique: process every returned instance, not just the first.
lnSuccess = loRest.AddQueryParam("MaxResults","100")
IF (lnSuccess <> 1) THEN
    ? "Could not set MaxResults."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

loSeenTokens = CreateObject('Chilkat.Hashtable')
lcNextToken = ""
lnMore = 1
lnPage = 0
DO WHILE (lnMore = 1)
    IF (lnPage = 1000) THEN
        ? "Page limit reached; enumeration is incomplete. Retain nextToken privately to resume."
        RELEASE loCredentials
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        RELEASE loConnection
        RELEASE loXml
        RELEASE loSeenTokens
        CANCEL
    ENDIF

    lcResponseXml = loRest.FullRequestNoBody("GET","/")
    IF (loRest.LastMethodSuccess <> 1) THEN
        ? "Request did not complete; inspect diagnostics privately."
        RELEASE loCredentials
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        RELEASE loConnection
        RELEASE loXml
        RELEASE loSeenTokens
        CANCEL
    ENDIF

    lnSuccess = loXml.LoadXml(lcResponseXml)
    IF (loRest.ResponseStatusCode <> 200) THEN
        ? "EC2 HTTP status: " + STR(loRest.ResponseStatusCode)
        IF (lnSuccess = 1) THEN
            IF (loXml.HasChildWithTag("Errors|Error|Code") = 1) THEN
                lcErrorCode = loXml.GetChildContent("Errors|Error|Code")
                ? "AWS error code: " + lcErrorCode
            ENDIF

            IF (loXml.HasChildWithTag("RequestID") = 1) THEN
                ? "AWS request ID: " + loXml.GetChildContent("RequestID")
            ENDIF

        ENDIF

        *  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.
        RELEASE loCredentials
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        RELEASE loConnection
        RELEASE loXml
        RELEASE loSeenTokens
        CANCEL
    ENDIF

    IF (lnSuccess <> 1) THEN
        ? "Expected a well-formed XML response."
        RELEASE loCredentials
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        RELEASE loConnection
        RELEASE loXml
        RELEASE loSeenTokens
        CANCEL
    ENDIF

    IF (loXml.Tag <> "DescribeInstancesResponse") THEN
        ? "Unexpected EC2 response element."
        RELEASE loCredentials
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        RELEASE loConnection
        RELEASE loXml
        RELEASE loSeenTokens
        CANCEL
    ENDIF

    IF ((loXml.HasChildWithTag("requestId") <> 1) OR (loXml.GetChildContent("requestId") = "")) THEN
        ? "Missing or empty requestId."
        RELEASE loCredentials
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        RELEASE loConnection
        RELEASE loXml
        RELEASE loSeenTokens
        CANCEL
    ENDIF

    ? "AWS request ID: " + loXml.GetChildContent("requestId")
    IF (loXml.HasChildWithTag("reservationSet") <> 1) THEN
        ? "Expected reservationSet."
        RELEASE loCredentials
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        RELEASE loConnection
        RELEASE loXml
        RELEASE loSeenTokens
        CANCEL
    ENDIF

    i = 0
    DO WHILE (i < loXml.NumChildrenAt("reservationSet"))
        loXml.I = i
        j = 0
        DO WHILE (j < loXml.NumChildrenAt("reservationSet|item[i]|instancesSet"))
            loXml.J = j
            IF ((loXml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|instanceId") <> 1) OR (loXml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|instanceId") = "")) THEN
                ? "Missing or empty reservationSet|item[i]|instancesSet|item[j]|instanceId."
                RELEASE loCredentials
                RELEASE loEndpoint
                RELEASE loAws
                RELEASE loRest
                RELEASE loConnection
                RELEASE loXml
                RELEASE loSeenTokens
                CANCEL
            ENDIF

            ? "Instance ID: " + loXml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|instanceId")
            IF (loXml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|instanceState|name") = 1) THEN
                ? "State: " + loXml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|instanceState|name")
            ENDIF

            IF (loXml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|instanceType") = 1) THEN
                ? "Type: " + loXml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|instanceType")
            ENDIF

            IF (loXml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|imageId") = 1) THEN
                ? "AMI: " + loXml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|imageId")
            ENDIF

            IF (loXml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|privateIpAddress") = 1) THEN
                ? "Private IPv4: " + loXml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|privateIpAddress")
            ENDIF

            IF (loXml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|ipAddress") = 1) THEN
                ? "Public IPv4: " + loXml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|ipAddress")
            ENDIF

            IF (loXml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|privateDnsName") = 1) THEN
                ? "Private DNS: " + loXml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|privateDnsName")
            ENDIF

            IF (loXml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|dnsName") = 1) THEN
                ? "Public DNS: " + loXml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|dnsName")
            ENDIF

            IF (loXml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|subnetId") = 1) THEN
                ? "Subnet: " + loXml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|subnetId")
            ENDIF

            IF (loXml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|vpcId") = 1) THEN
                ? "VPC: " + loXml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|vpcId")
            ENDIF

            k = 0
            DO WHILE (k < loXml.NumChildrenAt("reservationSet|item[i]|instancesSet|item[j]|tagSet"))
                loXml.K = k
                IF ((loXml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key") <> 1) OR (loXml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key") = "")) THEN
                    ? "Missing or empty reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key."
                    RELEASE loCredentials
                    RELEASE loEndpoint
                    RELEASE loAws
                    RELEASE loRest
                    RELEASE loConnection
                    RELEASE loXml
                    RELEASE loSeenTokens
                    CANCEL
                ENDIF

                ? "Tag key: " + loXml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key")
                IF (loXml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|value") = 1) THEN
                    ? "Tag value: " + loXml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|value")
                ENDIF

                k = k + 1
            ENDDO
            j = j + 1
        ENDDO
        i = i + 1
    ENDDO
    lnPage = lnPage + 1
    lnMore = 0
    lcNextToken = ""
    IF (loXml.HasChildWithTag("nextToken") = 1) THEN
        lcNextToken = loXml.GetChildContent("nextToken")
    ENDIF

    IF (lcNextToken <> "") THEN
        IF (loSeenTokens.Contains(lcNextToken) = 1) THEN
            ? "Repeated pagination token; enumeration is incomplete."
            RELEASE loCredentials
            RELEASE loEndpoint
            RELEASE loAws
            RELEASE loRest
            RELEASE loConnection
            RELEASE loXml
            RELEASE loSeenTokens
            CANCEL
        ENDIF

        lnSuccess = loSeenTokens.AddInt(lcNextToken,1)
        IF (lnSuccess <> 1) THEN
            ? "Could not track pages."
            RELEASE loCredentials
            RELEASE loEndpoint
            RELEASE loAws
            RELEASE loRest
            RELEASE loConnection
            RELEASE loXml
            RELEASE loSeenTokens
            CANCEL
        ENDIF

        IF (lnPage > 1) THEN
            lnSuccess = loRest.RemoveQueryParam("NextToken")
            IF (lnSuccess <> 1) THEN
                ? "Could not replace pagination token."
                RELEASE loCredentials
                RELEASE loEndpoint
                RELEASE loAws
                RELEASE loRest
                RELEASE loConnection
                RELEASE loXml
                RELEASE loSeenTokens
                CANCEL
            ENDIF

        ENDIF

        lnSuccess = loRest.AddQueryParam("NextToken",lcNextToken)
        IF (lnSuccess <> 1) THEN
            ? "Could not set NextToken."
            RELEASE loCredentials
            RELEASE loEndpoint
            RELEASE loAws
            RELEASE loRest
            RELEASE loConnection
            RELEASE loXml
            RELEASE loSeenTokens
            CANCEL
        ENDIF

        lnMore = 1
    ENDIF

ENDDO
? "Enumeration complete."

RELEASE loCredentials
RELEASE loEndpoint
RELEASE loAws
RELEASE loRest
RELEASE loConnection
RELEASE loXml
RELEASE loSeenTokens