Sample code for 30+ languages & platforms
Xojo Plugin Requires Chilkat v11.6.0+

Amazon EC2: List EBS Volumes and Instance Attachments

See more Amazon EC2 Examples

Inventory EBS volumes in this region, including unattached volumes, encryption, capacity, and attachments. Preserve IDs and numeric response text as strings. Multi-Attach volumes can have multiple attachment entries. The requested device name can differ from the guest OS device name. An attached volume is not proof that its filesystem is mounted. Unattached volumes still incur storage charges; this example does not detach or delete them.

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:DescribeVolumes. 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.

DescribeVolumes reference

Chilkat Xojo Plugin Downloads

Xojo Plugin
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
Dim success As Boolean
success = 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
    System.DebugLog("Could not load private AWS credentials.")
    Return
End If

If ((credentials.JsonTypeOf("access_key") <> 1) Or (credentials.StringOf("access_key") = "")) Then
    System.DebugLog("Missing or invalid access_key.")
    Return
End If

If ((credentials.JsonTypeOf("secret_key") <> 1) Or (credentials.StringOf("secret_key") = "")) Then
    System.DebugLog("Missing or invalid secret_key.")
    Return
End If

//  Set this once to the region containing the instances.
Dim region As String
region = "us-west-2"
Dim endpoint As New Chilkat.StringBuilder
success = endpoint.Append("ec2.")
success = endpoint.Append(region)
success = 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
    System.DebugLog("Could not configure AWS signing.")
    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 (credentials.HasMember("session_token") = True) Then
    If (credentials.JsonTypeOf("session_token") <> 1) Then
        System.DebugLog("session_token must be a string.")
        Return
    End If

    If (credentials.StringOf("session_token") <> "") Then
        success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"))
        If (success <> True) Then
            System.DebugLog("Could not set the session-token parameter.")
            Return
        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
    System.DebugLog("TLS connection failed; inspect diagnostics privately.")
    Return
End If

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

Dim responseXml As String
responseXml = ""
Dim errorCode As String
errorCode = ""
Dim i As Int32
i = 0
Dim j As Int32
j = 0
success = rest.AddQueryParam("Action","DescribeVolumes")
If (success <> True) Then
    System.DebugLog("Could not set Action.")
    Return
End If

//  To limit this inventory, add Filter.1.Name = "attachment.instance-id"
//  and Filter.1.Value.1 = the desired instance ID before sending requests.
success = rest.AddQueryParam("MaxResults","100")
If (success <> True) Then
    System.DebugLog("Could not set MaxResults.")
    Return
End If

Dim seenTokens As New Chilkat.Hashtable
Dim nextToken As String
nextToken = ""
Dim more As Boolean
more = True
Dim page As Int32
page = 0
While (more = True)
    If (page = 1000) Then
        System.DebugLog("Page limit reached; enumeration is incomplete. Retain nextToken privately to resume.")
        Return
    End If

    responseXml = rest.FullRequestNoBody("GET","/")
    If (rest.LastMethodSuccess <> True) Then
        System.DebugLog("Request did not complete; inspect diagnostics privately.")
        Return
    End If

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

            If (xml.HasChildWithTag("RequestID") = True) Then
                System.DebugLog("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.
        Return
    End If

    If (success <> True) Then
        System.DebugLog("Expected a well-formed XML response.")
        Return
    End If

    If (xml.Tag <> "DescribeVolumesResponse") Then
        System.DebugLog("Unexpected EC2 response element.")
        Return
    End If

    If ((xml.HasChildWithTag("requestId") <> True) Or (xml.GetChildContent("requestId") = "")) Then
        System.DebugLog("Missing or empty requestId.")
        Return
    End If

    System.DebugLog("AWS request ID: " + xml.GetChildContent("requestId"))
    If (xml.HasChildWithTag("volumeSet") <> True) Then
        System.DebugLog("Expected volumeSet.")
        Return
    End If

    i = 0
    While (i < xml.NumChildrenAt("volumeSet"))
        xml.I = i
        If ((xml.HasChildWithTag("volumeSet|item[i]|volumeId") <> True) Or (xml.GetChildContent("volumeSet|item[i]|volumeId") = "")) Then
            System.DebugLog("Missing or empty volumeSet|item[i]|volumeId.")
            Return
        End If

        System.DebugLog("Volume ID: " + xml.GetChildContent("volumeSet|item[i]|volumeId"))
        If (xml.HasChildWithTag("volumeSet|item[i]|status") = True) Then
            System.DebugLog("State: " + xml.GetChildContent("volumeSet|item[i]|status"))
        End If

        If (xml.HasChildWithTag("volumeSet|item[i]|size") = True) Then
            System.DebugLog("GiB: " + xml.GetChildContent("volumeSet|item[i]|size"))
        End If

        If (xml.HasChildWithTag("volumeSet|item[i]|volumeType") = True) Then
            System.DebugLog("Type: " + xml.GetChildContent("volumeSet|item[i]|volumeType"))
        End If

        If (xml.HasChildWithTag("volumeSet|item[i]|availabilityZone") = True) Then
            System.DebugLog("Availability Zone: " + xml.GetChildContent("volumeSet|item[i]|availabilityZone"))
        End If

        If (xml.HasChildWithTag("volumeSet|item[i]|encrypted") = True) Then
            System.DebugLog("Encrypted: " + xml.GetChildContent("volumeSet|item[i]|encrypted"))
        End If

        If (xml.HasChildWithTag("volumeSet|item[i]|kmsKeyId") = True) Then
            System.DebugLog("KMS key: " + xml.GetChildContent("volumeSet|item[i]|kmsKeyId"))
        End If

        If (xml.HasChildWithTag("volumeSet|item[i]|iops") = True) Then
            System.DebugLog("IOPS: " + xml.GetChildContent("volumeSet|item[i]|iops"))
        End If

        If (xml.HasChildWithTag("volumeSet|item[i]|throughput") = True) Then
            System.DebugLog("Throughput MiB/s: " + xml.GetChildContent("volumeSet|item[i]|throughput"))
        End If

        j = 0
        While (j < xml.NumChildrenAt("volumeSet|item[i]|attachmentSet"))
            xml.J = j
            If (xml.HasChildWithTag("volumeSet|item[i]|attachmentSet|item[j]|instanceId") = True) Then
                System.DebugLog("Attached instance: " + xml.GetChildContent("volumeSet|item[i]|attachmentSet|item[j]|instanceId"))
            End If

            If (xml.HasChildWithTag("volumeSet|item[i]|attachmentSet|item[j]|device") = True) Then
                System.DebugLog("Requested device: " + xml.GetChildContent("volumeSet|item[i]|attachmentSet|item[j]|device"))
            End If

            If (xml.HasChildWithTag("volumeSet|item[i]|attachmentSet|item[j]|status") = True) Then
                System.DebugLog("Attachment state: " + xml.GetChildContent("volumeSet|item[i]|attachmentSet|item[j]|status"))
            End If

            If (xml.HasChildWithTag("volumeSet|item[i]|attachmentSet|item[j]|deleteOnTermination") = True) Then
                System.DebugLog("Delete on termination: " + xml.GetChildContent("volumeSet|item[i]|attachmentSet|item[j]|deleteOnTermination"))
            End If

            j = j + 1
        Wend
        i = i + 1
    Wend
    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
            System.DebugLog("Repeated pagination token; enumeration is incomplete.")
            Return
        End If

        success = seenTokens.AddInt(nextToken,1)
        If (success <> True) Then
            System.DebugLog("Could not track pages.")
            Return
        End If

        If (page > 1) Then
            success = rest.RemoveQueryParam("NextToken")
            If (success <> True) Then
                System.DebugLog("Could not replace pagination token.")
                Return
            End If

        End If

        success = rest.AddQueryParam("NextToken",nextToken)
        If (success <> True) Then
            System.DebugLog("Could not set NextToken.")
            Return
        End If

        more = True
    End If

Wend
System.DebugLog("Enumeration complete.")