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

PowerBuilder
integer li_rc
long li_Success
oleobject loo_Credentials
string ls_Region
oleobject loo_Endpoint
oleobject loo_Aws
oleobject loo_Rest
oleobject loo_Connection
oleobject loo_Xml
string ls_ResponseXml
string ls_ErrorCode
string ls_InstanceName
long i
long j
long k
oleobject loo_SeenTokens
string ls_NextToken
long li_More
long li_Page

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
li_Success = 0
//  Private configuration, not a file in public web content or source control.
//  Load current IAM credentials authorized for the EC2 operation.
loo_Credentials = create oleobject
li_rc = loo_Credentials.ConnectToNewObject("Chilkat.JsonObject")
if li_rc < 0 then
    destroy loo_Credentials
    MessageBox("Error","Connecting to COM object failed")
    return
end if
loo_Credentials.Strict = 1
li_Success = loo_Credentials.LoadFile("qa_data/aws/ec2.json")
if li_Success <> 1 then
    Write-Debug "Could not load private AWS credentials."
    destroy loo_Credentials
    return
end if

if (loo_Credentials.JsonTypeOf("access_key") <> 1) OR (loo_Credentials.StringOf("access_key") = "") then
    Write-Debug "Missing or invalid access_key."
    destroy loo_Credentials
    return
end if

if (loo_Credentials.JsonTypeOf("secret_key") <> 1) OR (loo_Credentials.StringOf("secret_key") = "") then
    Write-Debug "Missing or invalid secret_key."
    destroy loo_Credentials
    return
end if

//  Set this once to the region containing the instances.
ls_Region = "us-west-2"
loo_Endpoint = create oleobject
li_rc = loo_Endpoint.ConnectToNewObject("Chilkat.StringBuilder")

loo_Endpoint.Append("ec2.")
loo_Endpoint.Append(ls_Region)
loo_Endpoint.Append(".amazonaws.com")
loo_Aws = create oleobject
li_rc = loo_Aws.ConnectToNewObject("Chilkat.AuthAws")

loo_Aws.AccessKey = loo_Credentials.StringOf("access_key")
loo_Aws.SecretKey = loo_Credentials.StringOf("secret_key")
loo_Aws.Region = ls_Region
loo_Aws.ServiceName = "ec2"
loo_Aws.SignatureVersion = 4
loo_Rest = create oleobject
li_rc = loo_Rest.ConnectToNewObject("Chilkat.Rest")

loo_Rest.ConnectTimeoutMs = 20000
loo_Rest.IdleTimeoutMs = 60000
li_Success = loo_Rest.SetAuthAws(loo_Aws)
if li_Success <> 1 then
    Write-Debug "Could not configure AWS signing."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    return
end if

//  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 loo_Credentials.HasMember("session_token") = 1 then
    if loo_Credentials.JsonTypeOf("session_token") <> 1 then
        Write-Debug "session_token must be a string."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        return
    end if

    if loo_Credentials.StringOf("session_token") <> "" then
        li_Success = loo_Rest.AddQueryParam("X-Amz-Security-Token",loo_Credentials.StringOf("session_token"))
        if li_Success <> 1 then
            Write-Debug "Could not set the session-token parameter."
            destroy loo_Credentials
            destroy loo_Endpoint
            destroy loo_Aws
            destroy loo_Rest
            return
        end if

    end if

end if

//  Supply a Socket to explicitly enable TLS certificate verification.
loo_Connection = create oleobject
li_rc = loo_Connection.ConnectToNewObject("Chilkat.Socket")

loo_Connection.RequireSslCertVerify = 1
loo_Connection.MaxReadIdleMs = 60000
loo_Connection.MaxSendIdleMs = 60000
li_Success = loo_Connection.Connect(loo_Endpoint.GetAsString(),443,1,20000)
if li_Success <> 1 then
    Write-Debug "TLS connection failed; inspect diagnostics privately."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    return
end if

li_Success = loo_Rest.UseConnection(loo_Connection,1)
if li_Success <> 1 then
    Write-Debug "Could not attach the TLS connection."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    return
end if

//  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.
loo_Xml = create oleobject
li_rc = loo_Xml.ConnectToNewObject("Chilkat.Xml")

loo_Xml.Strict = 1
li_Success = loo_Rest.AddQueryParam("Version","2016-11-15")
if li_Success <> 1 then
    Write-Debug "Could not set Version."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    return
end if

ls_ResponseXml = ""
ls_ErrorCode = ""
ls_InstanceName = "example-instance"
i = 0
j = 0
k = 0
li_Success = loo_Rest.AddQueryParam("Action","DescribeInstances")
if li_Success <> 1 then
    Write-Debug "Could not set Action."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    return
end if

li_Success = loo_Rest.AddQueryParam("Filter.1.Name","tag:Name")
if li_Success <> 1 then
    Write-Debug "Could not set Filter.1.Name."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    return
end if

li_Success = loo_Rest.AddQueryParam("Filter.1.Value.1",ls_InstanceName)
if li_Success <> 1 then
    Write-Debug "Could not set Filter.1.Value.1."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    return
end if

li_Success = loo_Rest.AddQueryParam("Filter.2.Name","instance-state-name")
if li_Success <> 1 then
    Write-Debug "Could not set Filter.2.Name."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    return
end if

li_Success = loo_Rest.AddQueryParam("Filter.2.Value.1","running")
if li_Success <> 1 then
    Write-Debug "Could not set Filter.2.Value.1."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    return
end if

//  Filters are ANDed. Remove a filter deliberately to broaden the search.
//  Name tags are not unique: process every returned instance, not just the first.
li_Success = loo_Rest.AddQueryParam("MaxResults","100")
if li_Success <> 1 then
    Write-Debug "Could not set MaxResults."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    return
end if

loo_SeenTokens = create oleobject
li_rc = loo_SeenTokens.ConnectToNewObject("Chilkat.Hashtable")

ls_NextToken = ""
li_More = 1
li_Page = 0
do while (li_More = 1)
    if li_Page = 1000 then
        Write-Debug "Page limit reached; enumeration is incomplete. Retain nextToken privately to resume."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_SeenTokens
        return
    end if

    ls_ResponseXml = loo_Rest.FullRequestNoBody("GET","/")
    if loo_Rest.LastMethodSuccess <> 1 then
        Write-Debug "Request did not complete; inspect diagnostics privately."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_SeenTokens
        return
    end if

    li_Success = loo_Xml.LoadXml(ls_ResponseXml)
    if loo_Rest.ResponseStatusCode <> 200 then
        Write-Debug "EC2 HTTP status: " + string(loo_Rest.ResponseStatusCode)
        if li_Success = 1 then
            if loo_Xml.HasChildWithTag("Errors|Error|Code") = 1 then
                ls_ErrorCode = loo_Xml.GetChildContent("Errors|Error|Code")
                Write-Debug "AWS error code: " + ls_ErrorCode
            end if

            if loo_Xml.HasChildWithTag("RequestID") = 1 then
                Write-Debug "AWS request ID: " + loo_Xml.GetChildContent("RequestID")
            end if

        end if

        //  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.
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_SeenTokens
        return
    end if

    if li_Success <> 1 then
        Write-Debug "Expected a well-formed XML response."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_SeenTokens
        return
    end if

    if loo_Xml.Tag <> "DescribeInstancesResponse" then
        Write-Debug "Unexpected EC2 response element."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_SeenTokens
        return
    end if

    if (loo_Xml.HasChildWithTag("requestId") <> 1) OR (loo_Xml.GetChildContent("requestId") = "") then
        Write-Debug "Missing or empty requestId."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_SeenTokens
        return
    end if

    Write-Debug "AWS request ID: " + loo_Xml.GetChildContent("requestId")
    if loo_Xml.HasChildWithTag("reservationSet") <> 1 then
        Write-Debug "Expected reservationSet."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_SeenTokens
        return
    end if

    i = 0
    do while (i < loo_Xml.NumChildrenAt("reservationSet"))
        loo_Xml.I = i
        j = 0
        do while (j < loo_Xml.NumChildrenAt("reservationSet|item[i]|instancesSet"))
            loo_Xml.J = j
            if (loo_Xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|instanceId") <> 1) OR (loo_Xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|instanceId") = "") then
                Write-Debug "Missing or empty reservationSet|item[i]|instancesSet|item[j]|instanceId."
                destroy loo_Credentials
                destroy loo_Endpoint
                destroy loo_Aws
                destroy loo_Rest
                destroy loo_Connection
                destroy loo_Xml
                destroy loo_SeenTokens
                return
            end if

            Write-Debug "Instance ID: " + loo_Xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|instanceId")
            if loo_Xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|instanceState|name") = 1 then
                Write-Debug "State: " + loo_Xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|instanceState|name")
            end if

            if loo_Xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|instanceType") = 1 then
                Write-Debug "Type: " + loo_Xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|instanceType")
            end if

            if loo_Xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|imageId") = 1 then
                Write-Debug "AMI: " + loo_Xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|imageId")
            end if

            if loo_Xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|privateIpAddress") = 1 then
                Write-Debug "Private IPv4: " + loo_Xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|privateIpAddress")
            end if

            if loo_Xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|ipAddress") = 1 then
                Write-Debug "Public IPv4: " + loo_Xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|ipAddress")
            end if

            if loo_Xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|privateDnsName") = 1 then
                Write-Debug "Private DNS: " + loo_Xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|privateDnsName")
            end if

            if loo_Xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|dnsName") = 1 then
                Write-Debug "Public DNS: " + loo_Xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|dnsName")
            end if

            if loo_Xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|subnetId") = 1 then
                Write-Debug "Subnet: " + loo_Xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|subnetId")
            end if

            if loo_Xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|vpcId") = 1 then
                Write-Debug "VPC: " + loo_Xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|vpcId")
            end if

            k = 0
            do while (k < loo_Xml.NumChildrenAt("reservationSet|item[i]|instancesSet|item[j]|tagSet"))
                loo_Xml.K = k
                if (loo_Xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key") <> 1) OR (loo_Xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key") = "") then
                    Write-Debug "Missing or empty reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key."
                    destroy loo_Credentials
                    destroy loo_Endpoint
                    destroy loo_Aws
                    destroy loo_Rest
                    destroy loo_Connection
                    destroy loo_Xml
                    destroy loo_SeenTokens
                    return
                end if

                Write-Debug "Tag key: " + loo_Xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key")
                if loo_Xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|value") = 1 then
                    Write-Debug "Tag value: " + loo_Xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|value")
                end if

                k = k + 1
            loop
            j = j + 1
        loop
        i = i + 1
    loop
    li_Page = li_Page + 1
    li_More = 0
    ls_NextToken = ""
    if loo_Xml.HasChildWithTag("nextToken") = 1 then
        ls_NextToken = loo_Xml.GetChildContent("nextToken")
    end if

    if ls_NextToken <> "" then
        if loo_SeenTokens.Contains(ls_NextToken) = 1 then
            Write-Debug "Repeated pagination token; enumeration is incomplete."
            destroy loo_Credentials
            destroy loo_Endpoint
            destroy loo_Aws
            destroy loo_Rest
            destroy loo_Connection
            destroy loo_Xml
            destroy loo_SeenTokens
            return
        end if

        li_Success = loo_SeenTokens.AddInt(ls_NextToken,1)
        if li_Success <> 1 then
            Write-Debug "Could not track pages."
            destroy loo_Credentials
            destroy loo_Endpoint
            destroy loo_Aws
            destroy loo_Rest
            destroy loo_Connection
            destroy loo_Xml
            destroy loo_SeenTokens
            return
        end if

        if li_Page > 1 then
            li_Success = loo_Rest.RemoveQueryParam("NextToken")
            if li_Success <> 1 then
                Write-Debug "Could not replace pagination token."
                destroy loo_Credentials
                destroy loo_Endpoint
                destroy loo_Aws
                destroy loo_Rest
                destroy loo_Connection
                destroy loo_Xml
                destroy loo_SeenTokens
                return
            end if

        end if

        li_Success = loo_Rest.AddQueryParam("NextToken",ls_NextToken)
        if li_Success <> 1 then
            Write-Debug "Could not set NextToken."
            destroy loo_Credentials
            destroy loo_Endpoint
            destroy loo_Aws
            destroy loo_Rest
            destroy loo_Connection
            destroy loo_Xml
            destroy loo_SeenTokens
            return
        end if

        li_More = 1
    end if

loop
Write-Debug "Enumeration complete."


destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Xml
destroy loo_SeenTokens