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

Amazon EC2: Check Instance Health and Scheduled Events

See more Amazon EC2 Examples

Read instance state, health summaries, and scheduled events across one account/region. Follow nextToken through every page, including an empty page with a token. A repeated token or the demonstration's 1000-page bound reports incomplete enumeration.

IncludeAllInstances includes non-running instances; it does not mean ignore explicit IDs. This example omits IDs and uses MaxResults=100. To select up to 100 explicit IDs, remove MaxResults and supply InstanceId.N. Keep following a returned token.

State and health are different. System health concerns AWS infrastructure; instance health concerns the guest; attached EBS health concerns volume reachability. Optional application/performance summaries are displayed when supplied. Missing fields are not interpreted as healthy. Scheduled events can require maintenance planning. Running and ok do not replace application readiness checks. Paginated results are not an atomic snapshot.

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.

Required IAM action: ec2:DescribeInstanceStatus. DescribeInstanceStatus requires 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.

AWS 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 loSeenTokens
LOCAL lcNextToken
LOCAL lnMore
LOCAL lnPage
LOCAL lcResponseXml
LOCAL lcErrorCode
LOCAL i
LOCAL j

*  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

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

*  Include stopped and other non-running instances as well as running instances.
*  This flag does NOT override InstanceId.N filters.
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

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

*  To check up to 100 specific IDs instead: REMOVE MaxResults and add InstanceId.1, etc.
*  AWS does not allow MaxResults together with explicit InstanceId.N parameters.
loSeenTokens = CreateObject('Chilkat.Hashtable')
lcNextToken = ""
lnMore = 1
lnPage = 0
DO WHILE (lnMore = 1)
    IF (lnPage = 1000) THEN
        ? "Stopped at 1000 pages; status enumeration is incomplete."
        *  Save nextToken privately to resume. It is not a permanent checkpoint.
        RELEASE loCredentials
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        RELEASE loConnection
        RELEASE loXml
        RELEASE loSeenTokens
        CANCEL
    ENDIF

    lcResponseXml = loRest.FullRequestNoBody("GET","/")
    IF (loRest.LastMethodSuccess <> 1) THEN
        ? "Request did not complete; inspect diagnostics privately."
        RELEASE loCredentials
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        RELEASE loConnection
        RELEASE loXml
        RELEASE loSeenTokens
        CANCEL
    ENDIF

    lnSuccess = loXml.LoadXml(lcResponseXml)
    IF (loRest.ResponseStatusCode <> 200) THEN
        ? "EC2 HTTP status: " + STR(loRest.ResponseStatusCode)
        IF (lnSuccess = 1) THEN
            IF (loXml.HasChildWithTag("Errors|Error|Code") = 1) THEN
                lcErrorCode = loXml.GetChildContent("Errors|Error|Code")
                ? "AWS error code: " + lcErrorCode
            ENDIF

            IF (loXml.HasChildWithTag("RequestID") = 1) THEN
                ? "AWS request ID: " + loXml.GetChildContent("RequestID")
            ENDIF

        ENDIF

        *  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.
        RELEASE loCredentials
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        RELEASE loConnection
        RELEASE loXml
        RELEASE loSeenTokens
        CANCEL
    ENDIF

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

    IF (loXml.Tag <> "DescribeInstanceStatusResponse") THEN
        ? "Unexpected EC2 response element."
        RELEASE loCredentials
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        RELEASE loConnection
        RELEASE loXml
        RELEASE loSeenTokens
        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
        RELEASE loSeenTokens
        CANCEL
    ENDIF

    ? "AWS request ID: " + loXml.GetChildContent("requestId")
    IF (loXml.HasChildWithTag("instanceStatusSet") <> 1) THEN
        ? "Expected instanceStatusSet."
        RELEASE loCredentials
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        RELEASE loConnection
        RELEASE loXml
        RELEASE loSeenTokens
        CANCEL
    ENDIF

    i = 0
    DO WHILE (i < loXml.NumChildrenAt("instanceStatusSet"))
        loXml.I = i
        IF ((loXml.HasChildWithTag("instanceStatusSet|item[i]|instanceId") <> 1) OR (loXml.GetChildContent("instanceStatusSet|item[i]|instanceId") = "")) THEN
            ? "Missing or empty instanceStatusSet|item[i]|instanceId."
            RELEASE loCredentials
            RELEASE loEndpoint
            RELEASE loAws
            RELEASE loRest
            RELEASE loConnection
            RELEASE loXml
            RELEASE loSeenTokens
            CANCEL
        ENDIF

        ? "Instance: " + loXml.GetChildContent("instanceStatusSet|item[i]|instanceId")
        *  Read by element name; XML response element order is not guaranteed.
        IF (loXml.HasChildWithTag("instanceStatusSet|item[i]|availabilityZone") = 1) THEN
            ? "Availability Zone: " + loXml.GetChildContent("instanceStatusSet|item[i]|availabilityZone")
        ENDIF

        IF (loXml.HasChildWithTag("instanceStatusSet|item[i]|instanceState|name") = 1) THEN
            ? "State: " + loXml.GetChildContent("instanceStatusSet|item[i]|instanceState|name")
        ENDIF

        IF (loXml.HasChildWithTag("instanceStatusSet|item[i]|systemStatus|status") = 1) THEN
            ? "System health: " + loXml.GetChildContent("instanceStatusSet|item[i]|systemStatus|status")
        ENDIF

        IF (loXml.HasChildWithTag("instanceStatusSet|item[i]|instanceStatus|status") = 1) THEN
            ? "Instance health: " + loXml.GetChildContent("instanceStatusSet|item[i]|instanceStatus|status")
        ENDIF

        IF (loXml.HasChildWithTag("instanceStatusSet|item[i]|attachedEbsStatus|status") = 1) THEN
            ? "Attached EBS health: " + loXml.GetChildContent("instanceStatusSet|item[i]|attachedEbsStatus|status")
        ENDIF

        IF (loXml.HasChildWithTag("instanceStatusSet|item[i]|applicationStatus|status") = 1) THEN
            ? "Application health: " + loXml.GetChildContent("instanceStatusSet|item[i]|applicationStatus|status")
        ENDIF

        IF (loXml.HasChildWithTag("instanceStatusSet|item[i]|performanceStatus|status") = 1) THEN
            ? "Performance health: " + loXml.GetChildContent("instanceStatusSet|item[i]|performanceStatus|status")
        ENDIF

        *  Scheduled events may be absent. Event IDs and timestamps remain strings.
        j = 0
        DO WHILE (j < loXml.NumChildrenAt("instanceStatusSet|item[i]|eventsSet"))
            loXml.J = j
            IF (loXml.HasChildWithTag("instanceStatusSet|item[i]|eventsSet|item[j]|instanceEventId") = 1) THEN
                ? "Event ID: " + loXml.GetChildContent("instanceStatusSet|item[i]|eventsSet|item[j]|instanceEventId")
            ENDIF

            IF (loXml.HasChildWithTag("instanceStatusSet|item[i]|eventsSet|item[j]|code") = 1) THEN
                ? "Event: " + loXml.GetChildContent("instanceStatusSet|item[i]|eventsSet|item[j]|code")
            ENDIF

            IF (loXml.HasChildWithTag("instanceStatusSet|item[i]|eventsSet|item[j]|description") = 1) THEN
                ? "Description: " + loXml.GetChildContent("instanceStatusSet|item[i]|eventsSet|item[j]|description")
            ENDIF

            IF (loXml.HasChildWithTag("instanceStatusSet|item[i]|eventsSet|item[j]|notBefore") = 1) THEN
                ? "Not before: " + loXml.GetChildContent("instanceStatusSet|item[i]|eventsSet|item[j]|notBefore")
            ENDIF

            IF (loXml.HasChildWithTag("instanceStatusSet|item[i]|eventsSet|item[j]|notAfter") = 1) THEN
                ? "Not after: " + loXml.GetChildContent("instanceStatusSet|item[i]|eventsSet|item[j]|notAfter")
            ENDIF

            IF (loXml.HasChildWithTag("instanceStatusSet|item[i]|eventsSet|item[j]|notBeforeDeadline") = 1) THEN
                ? "Rescheduling deadline: " + loXml.GetChildContent("instanceStatusSet|item[i]|eventsSet|item[j]|notBeforeDeadline")
            ENDIF

            j = j + 1
        ENDDO
        i = i + 1
    ENDDO
    lnPage = lnPage + 1
    lnMore = 0
    lcNextToken = ""
    IF (loXml.HasChildWithTag("nextToken") = 1) THEN
        lcNextToken = loXml.GetChildContent("nextToken")
    ENDIF

    IF (lcNextToken <> "") THEN
        IF (loSeenTokens.Contains(lcNextToken) = 1) THEN
            ? "Repeated pagination token; status enumeration is incomplete."
            RELEASE loCredentials
            RELEASE loEndpoint
            RELEASE loAws
            RELEASE loRest
            RELEASE loConnection
            RELEASE loXml
            RELEASE loSeenTokens
            CANCEL
        ENDIF

        lnSuccess = loSeenTokens.AddInt(lcNextToken,1)
        IF (lnSuccess <> 1) THEN
            ? "Could not track pagination."
            RELEASE loCredentials
            RELEASE loEndpoint
            RELEASE loAws
            RELEASE loRest
            RELEASE loConnection
            RELEASE loXml
            RELEASE loSeenTokens
            CANCEL
        ENDIF

        *  Replace the prior token; do not accumulate duplicate NextToken parameters.
        IF (lnPage > 1) THEN
            lnSuccess = loRest.RemoveQueryParam("NextToken")
            IF (lnSuccess <> 1) THEN
                ? "Could not remove the previous pagination token."
                RELEASE loCredentials
                RELEASE loEndpoint
                RELEASE loAws
                RELEASE loRest
                RELEASE loConnection
                RELEASE loXml
                RELEASE loSeenTokens
                CANCEL
            ENDIF

        ENDIF

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

        lnMore = 1
    ENDIF

ENDDO
? "Status enumeration complete."
*  A missing health field is unknown, not healthy. Even reported ok is not a
*  substitute for the application's own readiness check.

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