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

Amazon EC2: Wait for Instance State and Health Checks

See more Amazon EC2 Examples

Poll one instance until it is running with both system and instance health explicitly ok, or change desiredState to stopped for a state-only wait. Missing status entries and missing health fields are not success. A terminating state stops the wait. Application readiness needs its own probe; the two EC2 checks do not test your application.

Uses at most 60 reads with exponential delays capped at 10 seconds. HTTP timeouts add to elapsed time. Bounded retries cover throttling, selected service errors, and temporary InvalidInstanceID.NotFound after a recent launch; persistent absence can mean a wrong ID, account, or region. Authentication/permission failures stop immediately. The example makes no state-changing request.

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

DescribeInstanceStatus reference

Chilkat B4X Downloads

B4X
'  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 ChilkatJsonObject
credentials.Initialize
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/ec2.json")
If success <> True Then
    Log("Could not load private AWS credentials.")
    Return
End If

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

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

'  Set this once to the region containing the instances.
Dim region As String = "us-west-2"
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
endpoint.Append("ec2.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
Dim aws As ChilkatAuthAws
aws.Initialize
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "ec2"
aws.SignatureVersion = 4
Dim rest As ChilkatRest
rest.Initialize("rest")
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
success = rest.SetAuthAws(aws)
If success <> True Then
    Log("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
        Log("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
            Log("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 ChilkatSocket
connection.Initialize("connection")
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString, 443, True, 20000)
If success <> True Then
    Log("TLS connection failed; inspect diagnostics privately.")
    Return
End If

success = rest.UseConnection(connection, True)
If success <> True Then
    Log("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 ChilkatXml
xml.Initialize
xml.Strict = True
success = rest.AddQueryParam("Version", "2016-11-15")
If success <> True Then
    Log("Could not set Version.")
    Return
End If

Dim responseXml As String = ""
Dim errorCode As String = ""
Dim instanceId As String = "i-1234567890abcdef0"
'  Supported goals: "running" (with health checks) or "stopped" (state only).
Dim desiredState As String = "running"
If (desiredState <> "running") And (desiredState <> "stopped") Then
    Log("Choose running or stopped.")
    Return
End If

success = rest.AddQueryParam("Action", "DescribeInstanceStatus")
If success <> True Then
    Log("Could not set Action.")
    Return
End If

success = rest.AddQueryParam("InstanceId.1", instanceId)
If success <> True Then
    Log("Could not set InstanceId.1.")
    Return
End If

success = rest.AddQueryParam("IncludeAllInstances", "true")
If success <> True Then
    Log("Could not set IncludeAllInstances.")
    Return
End If

'  No MaxResults with explicit IDs. A missing entry is not readiness.
Dim state As String = ""
'  At most 60 attempts, with delays growing from 2 to 10 seconds.
'  HTTP timeouts add to total elapsed time. No busy loop or automatic write retry.
Dim attempt As Int = 0
Dim delayMs As Int = 2000
Dim retryRead As Boolean = False
Do While (attempt < 60)
    retryRead = False
    responseXml = rest.FullRequestNoBody("GET", "/")
    If rest.LastMethodSuccess <> True Then
        Log("Polling transport failed; resume the read later. No write was retried.")
        Return
    End If

    success = xml.LoadXml(responseXml)
    If rest.ResponseStatusCode <> 200 Then
        errorCode = ""
        If success = True Then
            If xml.HasChildWithTag("Errors|Error|Code") = True Then
                errorCode = xml.GetChildContent("Errors|Error|Code")
            End If

        End If

        If (errorCode = "RequestLimitExceeded") Or (errorCode = "InternalError") Or (errorCode = "ServiceUnavailable") Or (errorCode = "InvalidInstanceID.NotFound") Then
            retryRead = True
        Else
            Log("Polling failed: HTTP " & rest.ResponseStatusCode & "; AWS code: " & errorCode)
            Return
        End If

    End If

    If retryRead = False Then
        If success <> True Then
            Log("Expected a well-formed XML response.")
            Return
        End If

        If xml.Tag <> "DescribeInstanceStatusResponse" Then
            Log("Unexpected polling response.")
            Return
        End If

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

        If xml.HasChildWithTag("instanceStatusSet") <> True Then
            Log("Expected instanceStatusSet.")
            Return
        End If

        If xml.NumChildrenAt("instanceStatusSet") > 0 Then
            If xml.NumChildrenAt("instanceStatusSet") <> 1 Then
                Log("Expected one instance status.")
                Return
            End If

            If (xml.HasChildWithTag("instanceStatusSet|item|instanceId") <> True) Or (xml.GetChildContent("instanceStatusSet|item|instanceId") = "") Then
                Log("Missing or empty instanceStatusSet|item|instanceId.")
                Return
            End If

            If xml.GetChildContent("instanceStatusSet|item|instanceId") <> instanceId Then
                Log("Unexpected instance ID.")
                Return
            End If

            If (xml.HasChildWithTag("instanceStatusSet|item|instanceState|name") <> True) Or (xml.GetChildContent("instanceStatusSet|item|instanceState|name") = "") Then
                Log("Missing or empty instanceStatusSet|item|instanceState|name.")
                Return
            End If

            state = xml.GetChildContent("instanceStatusSet|item|instanceState|name")
            Log("Observed state: " & state)
            If (state = "shutting-down") Or (state = "terminated") Then
                Log("Instance is terminating or terminated; requested readiness cannot be reached.")
                Return
            End If

            If state = desiredState Then
                If desiredState = "stopped" Then
                    Log("Instance reached stopped state.")
                    Return
                End If

                '  Both statuses must explicitly be ok. Missing/initializing/impaired is not ready.
                If (xml.GetChildContent("instanceStatusSet|item|systemStatus|status") = "ok") And (xml.GetChildContent("instanceStatusSet|item|instanceStatus|status") = "ok") Then
                    Log("Instance is running and both EC2 health checks are ok.")
                    Log("Check application readiness separately.")
                    Return
                End If

            End If

        End If

    End If

    attempt = attempt + 1
    If attempt < 60 Then
        connection.SleepMs(delayMs)
        If delayMs < 10000 Then
            delayMs = delayMs * 2
            If delayMs > 10000 Then
                delayMs = 10000
            End If

        End If

    End If

Loop
Log("Polling limit reached; completion has not been confirmed. Resume checking later.")