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

Visual FoxPro
LOCAL lnSuccess
LOCAL loCredentials
LOCAL lcRegion
LOCAL loEndpoint
LOCAL loAws
LOCAL loRest
LOCAL loConnection
LOCAL loXml
LOCAL lcResponseXml
LOCAL lcErrorCode
LOCAL lcInstanceId
LOCAL lcDesiredState
LOCAL lcState
LOCAL lnAttempt
LOCAL lnDelayMs
LOCAL lnRetryRead

*  Assumes Chilkat is unlocked. See Global Unlock Sample.
lnSuccess = 0
*  Private configuration, not a file in public web content or source control.
*  Load current IAM credentials authorized for the EC2 operation.
loCredentials = CreateObject('Chilkat.JsonObject')
loCredentials.Strict = 1
lnSuccess = loCredentials.LoadFile("qa_data/aws/ec2.json")
IF (lnSuccess <> 1) THEN
    ? "Could not load private AWS credentials."
    RELEASE loCredentials
    CANCEL
ENDIF

IF ((loCredentials.JsonTypeOf("access_key") <> 1) OR (loCredentials.StringOf("access_key") = "")) THEN
    ? "Missing or invalid access_key."
    RELEASE loCredentials
    CANCEL
ENDIF

IF ((loCredentials.JsonTypeOf("secret_key") <> 1) OR (loCredentials.StringOf("secret_key") = "")) THEN
    ? "Missing or invalid secret_key."
    RELEASE loCredentials
    CANCEL
ENDIF

*  Set this once to the region containing the instances.
lcRegion = "us-west-2"
loEndpoint = CreateObject('Chilkat.StringBuilder')
loEndpoint.Append("ec2.")
loEndpoint.Append(lcRegion)
loEndpoint.Append(".amazonaws.com")
loAws = CreateObject('Chilkat.AuthAws')
loAws.AccessKey = loCredentials.StringOf("access_key")
loAws.SecretKey = loCredentials.StringOf("secret_key")
loAws.Region = lcRegion
loAws.ServiceName = "ec2"
loAws.SignatureVersion = 4
loRest = CreateObject('Chilkat.Rest')
loRest.ConnectTimeoutMs = 20000
loRest.IdleTimeoutMs = 60000
lnSuccess = loRest.SetAuthAws(loAws)
IF (lnSuccess <> 1) THEN
    ? "Could not configure AWS signing."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    CANCEL
ENDIF

*  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 (loCredentials.HasMember("session_token") = 1) THEN
    IF (loCredentials.JsonTypeOf("session_token") <> 1) THEN
        ? "session_token must be a string."
        RELEASE loCredentials
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        CANCEL
    ENDIF

    IF (loCredentials.StringOf("session_token") <> "") THEN
        lnSuccess = loRest.AddQueryParam("X-Amz-Security-Token",loCredentials.StringOf("session_token"))
        IF (lnSuccess <> 1) THEN
            ? "Could not set the session-token parameter."
            RELEASE loCredentials
            RELEASE loEndpoint
            RELEASE loAws
            RELEASE loRest
            CANCEL
        ENDIF

    ENDIF

ENDIF

*  Supply a Socket to explicitly enable TLS certificate verification.
loConnection = CreateObject('Chilkat.Socket')
loConnection.RequireSslCertVerify = 1
loConnection.MaxReadIdleMs = 60000
loConnection.MaxSendIdleMs = 60000
lnSuccess = loConnection.Connect(loEndpoint.GetAsString(),443,1,20000)
IF (lnSuccess <> 1) THEN
    ? "TLS connection failed; inspect diagnostics privately."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    CANCEL
ENDIF

lnSuccess = loRest.UseConnection(loConnection,1)
IF (lnSuccess <> 1) THEN
    ? "Could not attach the TLS connection."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    CANCEL
ENDIF

*  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.
loXml = CreateObject('Chilkat.Xml')
loXml.Strict = 1
lnSuccess = loRest.AddQueryParam("Version","2016-11-15")
IF (lnSuccess <> 1) THEN
    ? "Could not set Version."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lcResponseXml = ""
lcErrorCode = ""
lcInstanceId = "i-1234567890abcdef0"
*  Supported goals: "running" (with health checks) or "stopped" (state only).
lcDesiredState = "running"
IF ((lcDesiredState <> "running") AND (lcDesiredState <> "stopped")) THEN
    ? "Choose running or stopped."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loRest.AddQueryParam("Action","DescribeInstanceStatus")
IF (lnSuccess <> 1) THEN
    ? "Could not set Action."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loRest.AddQueryParam("InstanceId.1",lcInstanceId)
IF (lnSuccess <> 1) THEN
    ? "Could not set InstanceId.1."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loRest.AddQueryParam("IncludeAllInstances","true")
IF (lnSuccess <> 1) THEN
    ? "Could not set IncludeAllInstances."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

*  No MaxResults with explicit IDs. A missing entry is not readiness.
lcState = ""
*  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.
lnAttempt = 0
lnDelayMs = 2000
lnRetryRead = 0
DO WHILE (lnAttempt < 60)
    lnRetryRead = 0
    lcResponseXml = loRest.FullRequestNoBody("GET","/")
    IF (loRest.LastMethodSuccess <> 1) THEN
        ? "Polling transport failed; resume the read later. No write was retried."
        RELEASE loCredentials
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        RELEASE loConnection
        RELEASE loXml
        CANCEL
    ENDIF

    lnSuccess = loXml.LoadXml(lcResponseXml)
    IF (loRest.ResponseStatusCode <> 200) THEN
        lcErrorCode = ""
        IF (lnSuccess = 1) THEN
            IF (loXml.HasChildWithTag("Errors|Error|Code") = 1) THEN
                lcErrorCode = loXml.GetChildContent("Errors|Error|Code")
            ENDIF

        ENDIF

        IF ((lcErrorCode = "RequestLimitExceeded") OR (lcErrorCode = "InternalError") OR (lcErrorCode = "ServiceUnavailable") OR (lcErrorCode = "InvalidInstanceID.NotFound")) THEN
            lnRetryRead = 1
        ELSE
            ? "Polling failed: HTTP " + STR(loRest.ResponseStatusCode) + "; AWS code: " + lcErrorCode
            RELEASE loCredentials
            RELEASE loEndpoint
            RELEASE loAws
            RELEASE loRest
            RELEASE loConnection
            RELEASE loXml
            CANCEL
        ENDIF

    ENDIF

    IF (lnRetryRead = 0) THEN
        IF (lnSuccess <> 1) THEN
            ? "Expected a well-formed XML response."
            RELEASE loCredentials
            RELEASE loEndpoint
            RELEASE loAws
            RELEASE loRest
            RELEASE loConnection
            RELEASE loXml
            CANCEL
        ENDIF

        IF (loXml.Tag <> "DescribeInstanceStatusResponse") THEN
            ? "Unexpected polling response."
            RELEASE loCredentials
            RELEASE loEndpoint
            RELEASE loAws
            RELEASE loRest
            RELEASE loConnection
            RELEASE loXml
            CANCEL
        ENDIF

        IF ((loXml.HasChildWithTag("requestId") <> 1) OR (loXml.GetChildContent("requestId") = "")) THEN
            ? "Missing or empty requestId."
            RELEASE loCredentials
            RELEASE loEndpoint
            RELEASE loAws
            RELEASE loRest
            RELEASE loConnection
            RELEASE loXml
            CANCEL
        ENDIF

        IF (loXml.HasChildWithTag("instanceStatusSet") <> 1) THEN
            ? "Expected instanceStatusSet."
            RELEASE loCredentials
            RELEASE loEndpoint
            RELEASE loAws
            RELEASE loRest
            RELEASE loConnection
            RELEASE loXml
            CANCEL
        ENDIF

        IF (loXml.NumChildrenAt("instanceStatusSet") > 0) THEN
            IF (loXml.NumChildrenAt("instanceStatusSet") <> 1) THEN
                ? "Expected one instance status."
                RELEASE loCredentials
                RELEASE loEndpoint
                RELEASE loAws
                RELEASE loRest
                RELEASE loConnection
                RELEASE loXml
                CANCEL
            ENDIF

            IF ((loXml.HasChildWithTag("instanceStatusSet|item|instanceId") <> 1) OR (loXml.GetChildContent("instanceStatusSet|item|instanceId") = "")) THEN
                ? "Missing or empty instanceStatusSet|item|instanceId."
                RELEASE loCredentials
                RELEASE loEndpoint
                RELEASE loAws
                RELEASE loRest
                RELEASE loConnection
                RELEASE loXml
                CANCEL
            ENDIF

            IF (loXml.GetChildContent("instanceStatusSet|item|instanceId") <> lcInstanceId) THEN
                ? "Unexpected instance ID."
                RELEASE loCredentials
                RELEASE loEndpoint
                RELEASE loAws
                RELEASE loRest
                RELEASE loConnection
                RELEASE loXml
                CANCEL
            ENDIF

            IF ((loXml.HasChildWithTag("instanceStatusSet|item|instanceState|name") <> 1) OR (loXml.GetChildContent("instanceStatusSet|item|instanceState|name") = "")) THEN
                ? "Missing or empty instanceStatusSet|item|instanceState|name."
                RELEASE loCredentials
                RELEASE loEndpoint
                RELEASE loAws
                RELEASE loRest
                RELEASE loConnection
                RELEASE loXml
                CANCEL
            ENDIF

            lcState = loXml.GetChildContent("instanceStatusSet|item|instanceState|name")
            ? "Observed state: " + lcState
            IF ((lcState = "shutting-down") OR (lcState = "terminated")) THEN
                ? "Instance is terminating or terminated; requested readiness cannot be reached."
                RELEASE loCredentials
                RELEASE loEndpoint
                RELEASE loAws
                RELEASE loRest
                RELEASE loConnection
                RELEASE loXml
                CANCEL
            ENDIF

            IF (lcState = lcDesiredState) THEN
                IF (lcDesiredState = "stopped") THEN
                    ? "Instance reached stopped state."
                    RELEASE loCredentials
                    RELEASE loEndpoint
                    RELEASE loAws
                    RELEASE loRest
                    RELEASE loConnection
                    RELEASE loXml
                    CANCEL
                ENDIF

                *  Both statuses must explicitly be ok. Missing/initializing/impaired is not ready.
                IF ((loXml.GetChildContent("instanceStatusSet|item|systemStatus|status") = "ok") AND (loXml.GetChildContent("instanceStatusSet|item|instanceStatus|status") = "ok")) THEN
                    ? "Instance is running and both EC2 health checks are ok."
                    ? "Check application readiness separately."
                    RELEASE loCredentials
                    RELEASE loEndpoint
                    RELEASE loAws
                    RELEASE loRest
                    RELEASE loConnection
                    RELEASE loXml
                    CANCEL
                ENDIF

            ENDIF

        ENDIF

    ENDIF

    lnAttempt = lnAttempt + 1
    IF (lnAttempt < 60) THEN
        loConnection.SleepMs(lnDelayMs)
        IF (lnDelayMs < 10000) THEN
            lnDelayMs = lnDelayMs * 2
            IF (lnDelayMs > 10000) THEN
                lnDelayMs = 10000
            ENDIF

        ENDIF

    ENDIF

ENDDO
? "Polling limit reached; completion has not been confirmed. Resume checking later."

RELEASE loCredentials
RELEASE loEndpoint
RELEASE loAws
RELEASE loRest
RELEASE loConnection
RELEASE loXml