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

VB.NET
'  Assumes Chilkat is unlocked. See Global Unlock Sample.
Dim success As Boolean = False
'  Private configuration, not a file in public web content or source control.
'  Load current IAM credentials authorized for the EC2 operation.
Dim credentials As New Chilkat.JsonObject
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/ec2.json")
If (success <> True) Then
    Debug.WriteLine("Could not load private AWS credentials.")
    Exit Sub
End If

If ((credentials.JsonTypeOf("access_key") <> 1) Or (credentials.StringOf("access_key") = "")) Then
    Debug.WriteLine("Missing or invalid access_key.")
    Exit Sub
End If

If ((credentials.JsonTypeOf("secret_key") <> 1) Or (credentials.StringOf("secret_key") = "")) Then
    Debug.WriteLine("Missing or invalid secret_key.")
    Exit Sub
End If

'  Set this once to the region containing the instances.
Dim region As String = "us-west-2"
Dim endpoint As New Chilkat.StringBuilder
endpoint.Append("ec2.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
Dim aws As New Chilkat.AuthAws
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "ec2"
aws.SignatureVersion = 4
Dim rest As New Chilkat.Rest
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
success = rest.SetAuthAws(aws)
If (success <> True) Then
    Debug.WriteLine("Could not configure AWS signing.")
    Exit Sub
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 (credentials.HasMember("session_token") = True) Then
    If (credentials.JsonTypeOf("session_token") <> 1) Then
        Debug.WriteLine("session_token must be a string.")
        Exit Sub
    End If

    If (credentials.StringOf("session_token") <> "") Then
        success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"))
        If (success <> True) Then
            Debug.WriteLine("Could not set the session-token parameter.")
            Exit Sub
        End If

    End If

End If

'  Supply a Socket to explicitly enable TLS certificate verification.
Dim connection As New Chilkat.Socket
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,True,20000)
If (success <> True) Then
    Debug.WriteLine("TLS connection failed; inspect diagnostics privately.")
    Exit Sub
End If

success = rest.UseConnection(connection,True)
If (success <> True) Then
    Debug.WriteLine("Could not attach the TLS connection.")
    Exit Sub
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.
Dim xml As New Chilkat.Xml
xml.Strict = True
success = rest.AddQueryParam("Version","2016-11-15")
If (success <> True) Then
    Debug.WriteLine("Could not set Version.")
    Exit Sub
End If

Dim responseXml As String = ""
Dim errorCode As String = ""
Dim instanceName As String = "example-instance"
Dim i As Integer = 0
Dim j As Integer = 0
Dim k As Integer = 0
success = rest.AddQueryParam("Action","DescribeInstances")
If (success <> True) Then
    Debug.WriteLine("Could not set Action.")
    Exit Sub
End If

success = rest.AddQueryParam("Filter.1.Name","tag:Name")
If (success <> True) Then
    Debug.WriteLine("Could not set Filter.1.Name.")
    Exit Sub
End If

success = rest.AddQueryParam("Filter.1.Value.1",instanceName)
If (success <> True) Then
    Debug.WriteLine("Could not set Filter.1.Value.1.")
    Exit Sub
End If

success = rest.AddQueryParam("Filter.2.Name","instance-state-name")
If (success <> True) Then
    Debug.WriteLine("Could not set Filter.2.Name.")
    Exit Sub
End If

success = rest.AddQueryParam("Filter.2.Value.1","running")
If (success <> True) Then
    Debug.WriteLine("Could not set Filter.2.Value.1.")
    Exit Sub
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.
success = rest.AddQueryParam("MaxResults","100")
If (success <> True) Then
    Debug.WriteLine("Could not set MaxResults.")
    Exit Sub
End If

Dim seenTokens As New Chilkat.Hashtable
Dim nextToken As String = ""
Dim more As Boolean = True
Dim page As Integer = 0
While (more = True)
    If (page = 1000) Then
        Debug.WriteLine("Page limit reached; enumeration is incomplete. Retain nextToken privately to resume.")
        Exit Sub
    End If

    responseXml = rest.FullRequestNoBody("GET","/")
    If (rest.LastMethodSuccess <> True) Then
        Debug.WriteLine("Request did not complete; inspect diagnostics privately.")
        Exit Sub
    End If

    success = xml.LoadXml(responseXml)
    If (rest.ResponseStatusCode <> 200) Then
        Debug.WriteLine("EC2 HTTP status: " & rest.ResponseStatusCode)
        If (success = True) Then
            If (xml.HasChildWithTag("Errors|Error|Code") = True) Then
                errorCode = xml.GetChildContent("Errors|Error|Code")
                Debug.WriteLine("AWS error code: " & errorCode)
            End If

            If (xml.HasChildWithTag("RequestID") = True) Then
                Debug.WriteLine("AWS request ID: " & 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.
        Exit Sub
    End If

    If (success <> True) Then
        Debug.WriteLine("Expected a well-formed XML response.")
        Exit Sub
    End If

    If (xml.Tag <> "DescribeInstancesResponse") Then
        Debug.WriteLine("Unexpected EC2 response element.")
        Exit Sub
    End If

    If ((xml.HasChildWithTag("requestId") <> True) Or (xml.GetChildContent("requestId") = "")) Then
        Debug.WriteLine("Missing or empty requestId.")
        Exit Sub
    End If

    Debug.WriteLine("AWS request ID: " & xml.GetChildContent("requestId"))
    If (xml.HasChildWithTag("reservationSet") <> True) Then
        Debug.WriteLine("Expected reservationSet.")
        Exit Sub
    End If

    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") <> True) Or (xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|instanceId") = "")) Then
                Debug.WriteLine("Missing or empty reservationSet|item[i]|instancesSet|item[j]|instanceId.")
                Exit Sub
            End If

            Debug.WriteLine("Instance ID: " & xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|instanceId"))
            If (xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|instanceState|name") = True) Then
                Debug.WriteLine("State: " & xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|instanceState|name"))
            End If

            If (xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|instanceType") = True) Then
                Debug.WriteLine("Type: " & xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|instanceType"))
            End If

            If (xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|imageId") = True) Then
                Debug.WriteLine("AMI: " & xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|imageId"))
            End If

            If (xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|privateIpAddress") = True) Then
                Debug.WriteLine("Private IPv4: " & xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|privateIpAddress"))
            End If

            If (xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|ipAddress") = True) Then
                Debug.WriteLine("Public IPv4: " & xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|ipAddress"))
            End If

            If (xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|privateDnsName") = True) Then
                Debug.WriteLine("Private DNS: " & xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|privateDnsName"))
            End If

            If (xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|dnsName") = True) Then
                Debug.WriteLine("Public DNS: " & xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|dnsName"))
            End If

            If (xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|subnetId") = True) Then
                Debug.WriteLine("Subnet: " & xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|subnetId"))
            End If

            If (xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|vpcId") = True) Then
                Debug.WriteLine("VPC: " & xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|vpcId"))
            End If

            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") <> True) Or (xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key") = "")) Then
                    Debug.WriteLine("Missing or empty reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key.")
                    Exit Sub
                End If

                Debug.WriteLine("Tag key: " & xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key"))
                If (xml.HasChildWithTag("reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|value") = True) Then
                    Debug.WriteLine("Tag value: " & xml.GetChildContent("reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|value"))
                End If

                k = k + 1
            End While
            j = j + 1
        End While
        i = i + 1
    End While
    page = page + 1
    more = False
    nextToken = ""
    If (xml.HasChildWithTag("nextToken") = True) Then
        nextToken = xml.GetChildContent("nextToken")
    End If

    If (nextToken <> "") Then
        If (seenTokens.Contains(nextToken) = True) Then
            Debug.WriteLine("Repeated pagination token; enumeration is incomplete.")
            Exit Sub
        End If

        success = seenTokens.AddInt(nextToken,1)
        If (success <> True) Then
            Debug.WriteLine("Could not track pages.")
            Exit Sub
        End If

        If (page > 1) Then
            success = rest.RemoveQueryParam("NextToken")
            If (success <> True) Then
                Debug.WriteLine("Could not replace pagination token.")
                Exit Sub
            End If

        End If

        success = rest.AddQueryParam("NextToken",nextToken)
        If (success <> True) Then
            Debug.WriteLine("Could not set NextToken.")
            Exit Sub
        End If

        more = True
    End If

End While
Debug.WriteLine("Enumeration complete.")