Sample code for 30+ languages & platforms
PowerBuilder 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 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_InstanceId
string ls_DesiredState
string ls_State
long li_Attempt
long li_DelayMs
long li_RetryRead

//  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_InstanceId = "i-1234567890abcdef0"
//  Supported goals: "running" (with health checks) or "stopped" (state only).
ls_DesiredState = "running"
if (ls_DesiredState <> "running") AND (ls_DesiredState <> "stopped") then
    Write-Debug "Choose running or stopped."
    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("Action","DescribeInstanceStatus")
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("InstanceId.1",ls_InstanceId)
if li_Success <> 1 then
    Write-Debug "Could not set InstanceId.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("IncludeAllInstances","true")
if li_Success <> 1 then
    Write-Debug "Could not set IncludeAllInstances."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    return
end if

//  No MaxResults with explicit IDs. A missing entry is not readiness.
ls_State = ""
//  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.
li_Attempt = 0
li_DelayMs = 2000
li_RetryRead = 0
do while (li_Attempt < 60)
    li_RetryRead = 0
    ls_ResponseXml = loo_Rest.FullRequestNoBody("GET","/")
    if loo_Rest.LastMethodSuccess <> 1 then
        Write-Debug "Polling transport failed; resume the read later. No write was retried."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        return
    end if

    li_Success = loo_Xml.LoadXml(ls_ResponseXml)
    if loo_Rest.ResponseStatusCode <> 200 then
        ls_ErrorCode = ""
        if li_Success = 1 then
            if loo_Xml.HasChildWithTag("Errors|Error|Code") = 1 then
                ls_ErrorCode = loo_Xml.GetChildContent("Errors|Error|Code")
            end if

        end if

        if (ls_ErrorCode = "RequestLimitExceeded") OR (ls_ErrorCode = "InternalError") OR (ls_ErrorCode = "ServiceUnavailable") OR (ls_ErrorCode = "InvalidInstanceID.NotFound") then
            li_RetryRead = 1
        else
            Write-Debug "Polling failed: HTTP " + string(loo_Rest.ResponseStatusCode) + "; AWS code: " + ls_ErrorCode
            destroy loo_Credentials
            destroy loo_Endpoint
            destroy loo_Aws
            destroy loo_Rest
            destroy loo_Connection
            destroy loo_Xml
            return
        end if

    end if

    if li_RetryRead = 0 then
        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
            return
        end if

        if loo_Xml.Tag <> "DescribeInstanceStatusResponse" then
            Write-Debug "Unexpected polling response."
            destroy loo_Credentials
            destroy loo_Endpoint
            destroy loo_Aws
            destroy loo_Rest
            destroy loo_Connection
            destroy loo_Xml
            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
            return
        end if

        if loo_Xml.HasChildWithTag("instanceStatusSet") <> 1 then
            Write-Debug "Expected instanceStatusSet."
            destroy loo_Credentials
            destroy loo_Endpoint
            destroy loo_Aws
            destroy loo_Rest
            destroy loo_Connection
            destroy loo_Xml
            return
        end if

        if loo_Xml.NumChildrenAt("instanceStatusSet") > 0 then
            if loo_Xml.NumChildrenAt("instanceStatusSet") <> 1 then
                Write-Debug "Expected one instance status."
                destroy loo_Credentials
                destroy loo_Endpoint
                destroy loo_Aws
                destroy loo_Rest
                destroy loo_Connection
                destroy loo_Xml
                return
            end if

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

            if loo_Xml.GetChildContent("instanceStatusSet|item|instanceId") <> ls_InstanceId then
                Write-Debug "Unexpected instance ID."
                destroy loo_Credentials
                destroy loo_Endpoint
                destroy loo_Aws
                destroy loo_Rest
                destroy loo_Connection
                destroy loo_Xml
                return
            end if

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

            ls_State = loo_Xml.GetChildContent("instanceStatusSet|item|instanceState|name")
            Write-Debug "Observed state: " + ls_State
            if (ls_State = "shutting-down") OR (ls_State = "terminated") then
                Write-Debug "Instance is terminating or terminated; requested readiness cannot be reached."
                destroy loo_Credentials
                destroy loo_Endpoint
                destroy loo_Aws
                destroy loo_Rest
                destroy loo_Connection
                destroy loo_Xml
                return
            end if

            if ls_State = ls_DesiredState then
                if ls_DesiredState = "stopped" then
                    Write-Debug "Instance reached stopped state."
                    destroy loo_Credentials
                    destroy loo_Endpoint
                    destroy loo_Aws
                    destroy loo_Rest
                    destroy loo_Connection
                    destroy loo_Xml
                    return
                end if

                //  Both statuses must explicitly be ok. Missing/initializing/impaired is not ready.
                if (loo_Xml.GetChildContent("instanceStatusSet|item|systemStatus|status") = "ok") AND (loo_Xml.GetChildContent("instanceStatusSet|item|instanceStatus|status") = "ok") then
                    Write-Debug "Instance is running and both EC2 health checks are ok."
                    Write-Debug "Check application readiness separately."
                    destroy loo_Credentials
                    destroy loo_Endpoint
                    destroy loo_Aws
                    destroy loo_Rest
                    destroy loo_Connection
                    destroy loo_Xml
                    return
                end if

            end if

        end if

    end if

    li_Attempt = li_Attempt + 1
    if li_Attempt < 60 then
        loo_Connection.SleepMs(li_DelayMs)
        if li_DelayMs < 10000 then
            li_DelayMs = li_DelayMs * 2
            if li_DelayMs > 10000 then
                li_DelayMs = 10000
            end if

        end if

    end if

loop
Write-Debug "Polling limit reached; completion has not been confirmed. Resume checking later."


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