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

PureBasic
IncludeFile "CkAuthAws.pb"
IncludeFile "CkJsonObject.pb"
IncludeFile "CkSocket.pb"
IncludeFile "CkXml.pb"
IncludeFile "CkHashtable.pb"
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkRest.pb"

Procedure ChilkatExample()

    ;  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success.i = 0
    ;  Private configuration, not a file in public web content or source control.
    ;  Load current IAM credentials authorized for the EC2 operation.
    credentials.i = CkJsonObject::ckCreate()
    If credentials.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkJsonObject::setCkStrict(credentials, 1)
    success = CkJsonObject::ckLoadFile(credentials,"qa_data/aws/ec2.json")
    If success <> 1
        Debug "Could not load private AWS credentials."
        CkJsonObject::ckDispose(credentials)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(credentials,"access_key") <> 1) OR (CkJsonObject::ckStringOf(credentials,"access_key") = "")
        Debug "Missing or invalid access_key."
        CkJsonObject::ckDispose(credentials)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(credentials,"secret_key") <> 1) OR (CkJsonObject::ckStringOf(credentials,"secret_key") = "")
        Debug "Missing or invalid secret_key."
        CkJsonObject::ckDispose(credentials)
        ProcedureReturn
    EndIf

    ;  Set this once to the region containing the instances.
    region.s = "us-west-2"
    endpoint.i = CkStringBuilder::ckCreate()
    If endpoint.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStringBuilder::ckAppend(endpoint,"ec2.")
    CkStringBuilder::ckAppend(endpoint,region)
    CkStringBuilder::ckAppend(endpoint,".amazonaws.com")
    aws.i = CkAuthAws::ckCreate()
    If aws.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkAuthAws::setCkAccessKey(aws, CkJsonObject::ckStringOf(credentials,"access_key"))
    CkAuthAws::setCkSecretKey(aws, CkJsonObject::ckStringOf(credentials,"secret_key"))
    CkAuthAws::setCkRegion(aws, region)
    CkAuthAws::setCkServiceName(aws, "ec2")
    CkAuthAws::setCkSignatureVersion(aws, 4)
    rest.i = CkRest::ckCreate()
    If rest.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkRest::setCkConnectTimeoutMs(rest, 20000)
    CkRest::setCkIdleTimeoutMs(rest, 60000)
    success = CkRest::ckSetAuthAws(rest,aws)
    If success <> 1
        Debug "Could not configure AWS signing."
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        ProcedureReturn
    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 CkJsonObject::ckHasMember(credentials,"session_token") = 1
        If CkJsonObject::ckJsonTypeOf(credentials,"session_token") <> 1
            Debug "session_token must be a string."
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(endpoint)
            CkAuthAws::ckDispose(aws)
            CkRest::ckDispose(rest)
            ProcedureReturn
        EndIf

        If CkJsonObject::ckStringOf(credentials,"session_token") <> ""
            success = CkRest::ckAddQueryParam(rest,"X-Amz-Security-Token",CkJsonObject::ckStringOf(credentials,"session_token"))
            If success <> 1
                Debug "Could not set the session-token parameter."
                CkJsonObject::ckDispose(credentials)
                CkStringBuilder::ckDispose(endpoint)
                CkAuthAws::ckDispose(aws)
                CkRest::ckDispose(rest)
                ProcedureReturn
            EndIf

        EndIf

    EndIf

    ;  Supply a Socket to explicitly enable TLS certificate verification.
    connection.i = CkSocket::ckCreate()
    If connection.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkSocket::setCkRequireSslCertVerify(connection, 1)
    CkSocket::setCkMaxReadIdleMs(connection, 60000)
    CkSocket::setCkMaxSendIdleMs(connection, 60000)
    success = CkSocket::ckConnect(connection,CkStringBuilder::ckGetAsString(endpoint),443,1,20000)
    If success <> 1
        Debug "TLS connection failed; inspect diagnostics privately."
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        ProcedureReturn
    EndIf

    success = CkRest::ckUseConnection(rest,connection,1)
    If success <> 1
        Debug "Could not attach the TLS connection."
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        ProcedureReturn
    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.
    xml.i = CkXml::ckCreate()
    If xml.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkXml::setCkStrict(xml, 1)
    success = CkRest::ckAddQueryParam(rest,"Version","2016-11-15")
    If success <> 1
        Debug "Could not set Version."
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        ProcedureReturn
    EndIf

    success = CkRest::ckAddQueryParam(rest,"Action","DescribeInstanceStatus")
    If success <> 1
        Debug "Could not set Action."
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        ProcedureReturn
    EndIf

    ;  Include stopped and other non-running instances as well as running instances.
    ;  This flag does NOT override InstanceId.N filters.
    success = CkRest::ckAddQueryParam(rest,"IncludeAllInstances","true")
    If success <> 1
        Debug "Could not set IncludeAllInstances."
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        ProcedureReturn
    EndIf

    success = CkRest::ckAddQueryParam(rest,"MaxResults","100")
    If success <> 1
        Debug "Could not set MaxResults."
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        ProcedureReturn
    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.
    seenTokens.i = CkHashtable::ckCreate()
    If seenTokens.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    nextToken.s = ""
    more.i = 1
    page.i = 0
    While (more = 1)
        If page = 1000
            Debug "Stopped at 1000 pages; status enumeration is incomplete."
            ;  Save nextToken privately to resume. It is not a permanent checkpoint.
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(endpoint)
            CkAuthAws::ckDispose(aws)
            CkRest::ckDispose(rest)
            CkSocket::ckDispose(connection)
            CkXml::ckDispose(xml)
            CkHashtable::ckDispose(seenTokens)
            ProcedureReturn
        EndIf

        responseXml.s = CkRest::ckFullRequestNoBody(rest,"GET","/")
        If CkRest::ckLastMethodSuccess(rest) <> 1
            Debug "Request did not complete; inspect diagnostics privately."
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(endpoint)
            CkAuthAws::ckDispose(aws)
            CkRest::ckDispose(rest)
            CkSocket::ckDispose(connection)
            CkXml::ckDispose(xml)
            CkHashtable::ckDispose(seenTokens)
            ProcedureReturn
        EndIf

        success = CkXml::ckLoadXml(xml,responseXml)
        If CkRest::ckResponseStatusCode(rest) <> 200
            Debug "EC2 HTTP status: " + Str(CkRest::ckResponseStatusCode(rest))
            If success = 1
                If CkXml::ckHasChildWithTag(xml,"Errors|Error|Code") = 1
                    errorCode.s = CkXml::ckGetChildContent(xml,"Errors|Error|Code")
                    Debug "AWS error code: " + errorCode
                EndIf

                If CkXml::ckHasChildWithTag(xml,"RequestID") = 1
                    Debug "AWS request ID: " + CkXml::ckGetChildContent(xml,"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.
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(endpoint)
            CkAuthAws::ckDispose(aws)
            CkRest::ckDispose(rest)
            CkSocket::ckDispose(connection)
            CkXml::ckDispose(xml)
            CkHashtable::ckDispose(seenTokens)
            ProcedureReturn
        EndIf

        If success <> 1
            Debug "Expected a well-formed XML response."
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(endpoint)
            CkAuthAws::ckDispose(aws)
            CkRest::ckDispose(rest)
            CkSocket::ckDispose(connection)
            CkXml::ckDispose(xml)
            CkHashtable::ckDispose(seenTokens)
            ProcedureReturn
        EndIf

        If CkXml::ckTag(xml) <> "DescribeInstanceStatusResponse"
            Debug "Unexpected EC2 response element."
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(endpoint)
            CkAuthAws::ckDispose(aws)
            CkRest::ckDispose(rest)
            CkSocket::ckDispose(connection)
            CkXml::ckDispose(xml)
            CkHashtable::ckDispose(seenTokens)
            ProcedureReturn
        EndIf

        If (CkXml::ckHasChildWithTag(xml,"requestId") <> 1) OR (CkXml::ckGetChildContent(xml,"requestId") = "")
            Debug "Missing or empty requestId."
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(endpoint)
            CkAuthAws::ckDispose(aws)
            CkRest::ckDispose(rest)
            CkSocket::ckDispose(connection)
            CkXml::ckDispose(xml)
            CkHashtable::ckDispose(seenTokens)
            ProcedureReturn
        EndIf

        Debug "AWS request ID: " + CkXml::ckGetChildContent(xml,"requestId")
        If CkXml::ckHasChildWithTag(xml,"instanceStatusSet") <> 1
            Debug "Expected instanceStatusSet."
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(endpoint)
            CkAuthAws::ckDispose(aws)
            CkRest::ckDispose(rest)
            CkSocket::ckDispose(connection)
            CkXml::ckDispose(xml)
            CkHashtable::ckDispose(seenTokens)
            ProcedureReturn
        EndIf

        i.i = 0
        While (i < CkXml::ckNumChildrenAt(xml,"instanceStatusSet"))
            CkXml::setCkI(xml, i)
            If (CkXml::ckHasChildWithTag(xml,"instanceStatusSet|item[i]|instanceId") <> 1) OR (CkXml::ckGetChildContent(xml,"instanceStatusSet|item[i]|instanceId") = "")
                Debug "Missing or empty instanceStatusSet|item[i]|instanceId."
                CkJsonObject::ckDispose(credentials)
                CkStringBuilder::ckDispose(endpoint)
                CkAuthAws::ckDispose(aws)
                CkRest::ckDispose(rest)
                CkSocket::ckDispose(connection)
                CkXml::ckDispose(xml)
                CkHashtable::ckDispose(seenTokens)
                ProcedureReturn
            EndIf

            Debug "Instance: " + CkXml::ckGetChildContent(xml,"instanceStatusSet|item[i]|instanceId")
            ;  Read by element name; XML response element order is not guaranteed.
            If CkXml::ckHasChildWithTag(xml,"instanceStatusSet|item[i]|availabilityZone") = 1
                Debug "Availability Zone: " + CkXml::ckGetChildContent(xml,"instanceStatusSet|item[i]|availabilityZone")
            EndIf

            If CkXml::ckHasChildWithTag(xml,"instanceStatusSet|item[i]|instanceState|name") = 1
                Debug "State: " + CkXml::ckGetChildContent(xml,"instanceStatusSet|item[i]|instanceState|name")
            EndIf

            If CkXml::ckHasChildWithTag(xml,"instanceStatusSet|item[i]|systemStatus|status") = 1
                Debug "System health: " + CkXml::ckGetChildContent(xml,"instanceStatusSet|item[i]|systemStatus|status")
            EndIf

            If CkXml::ckHasChildWithTag(xml,"instanceStatusSet|item[i]|instanceStatus|status") = 1
                Debug "Instance health: " + CkXml::ckGetChildContent(xml,"instanceStatusSet|item[i]|instanceStatus|status")
            EndIf

            If CkXml::ckHasChildWithTag(xml,"instanceStatusSet|item[i]|attachedEbsStatus|status") = 1
                Debug "Attached EBS health: " + CkXml::ckGetChildContent(xml,"instanceStatusSet|item[i]|attachedEbsStatus|status")
            EndIf

            If CkXml::ckHasChildWithTag(xml,"instanceStatusSet|item[i]|applicationStatus|status") = 1
                Debug "Application health: " + CkXml::ckGetChildContent(xml,"instanceStatusSet|item[i]|applicationStatus|status")
            EndIf

            If CkXml::ckHasChildWithTag(xml,"instanceStatusSet|item[i]|performanceStatus|status") = 1
                Debug "Performance health: " + CkXml::ckGetChildContent(xml,"instanceStatusSet|item[i]|performanceStatus|status")
            EndIf

            ;  Scheduled events may be absent. Event IDs and timestamps remain strings.
            j.i = 0
            While (j < CkXml::ckNumChildrenAt(xml,"instanceStatusSet|item[i]|eventsSet"))
                CkXml::setCkJ(xml, j)
                If CkXml::ckHasChildWithTag(xml,"instanceStatusSet|item[i]|eventsSet|item[j]|instanceEventId") = 1
                    Debug "Event ID: " + CkXml::ckGetChildContent(xml,"instanceStatusSet|item[i]|eventsSet|item[j]|instanceEventId")
                EndIf

                If CkXml::ckHasChildWithTag(xml,"instanceStatusSet|item[i]|eventsSet|item[j]|code") = 1
                    Debug "Event: " + CkXml::ckGetChildContent(xml,"instanceStatusSet|item[i]|eventsSet|item[j]|code")
                EndIf

                If CkXml::ckHasChildWithTag(xml,"instanceStatusSet|item[i]|eventsSet|item[j]|description") = 1
                    Debug "Description: " + CkXml::ckGetChildContent(xml,"instanceStatusSet|item[i]|eventsSet|item[j]|description")
                EndIf

                If CkXml::ckHasChildWithTag(xml,"instanceStatusSet|item[i]|eventsSet|item[j]|notBefore") = 1
                    Debug "Not before: " + CkXml::ckGetChildContent(xml,"instanceStatusSet|item[i]|eventsSet|item[j]|notBefore")
                EndIf

                If CkXml::ckHasChildWithTag(xml,"instanceStatusSet|item[i]|eventsSet|item[j]|notAfter") = 1
                    Debug "Not after: " + CkXml::ckGetChildContent(xml,"instanceStatusSet|item[i]|eventsSet|item[j]|notAfter")
                EndIf

                If CkXml::ckHasChildWithTag(xml,"instanceStatusSet|item[i]|eventsSet|item[j]|notBeforeDeadline") = 1
                    Debug "Rescheduling deadline: " + CkXml::ckGetChildContent(xml,"instanceStatusSet|item[i]|eventsSet|item[j]|notBeforeDeadline")
                EndIf

                j = j + 1
            Wend
            i = i + 1
        Wend
        page = page + 1
        more = 0
        nextToken = ""
        If CkXml::ckHasChildWithTag(xml,"nextToken") = 1
            nextToken = CkXml::ckGetChildContent(xml,"nextToken")
        EndIf

        If nextToken <> ""
            If CkHashtable::ckContains(seenTokens,nextToken) = 1
                Debug "Repeated pagination token; status enumeration is incomplete."
                CkJsonObject::ckDispose(credentials)
                CkStringBuilder::ckDispose(endpoint)
                CkAuthAws::ckDispose(aws)
                CkRest::ckDispose(rest)
                CkSocket::ckDispose(connection)
                CkXml::ckDispose(xml)
                CkHashtable::ckDispose(seenTokens)
                ProcedureReturn
            EndIf

            success = CkHashtable::ckAddInt(seenTokens,nextToken,1)
            If success <> 1
                Debug "Could not track pagination."
                CkJsonObject::ckDispose(credentials)
                CkStringBuilder::ckDispose(endpoint)
                CkAuthAws::ckDispose(aws)
                CkRest::ckDispose(rest)
                CkSocket::ckDispose(connection)
                CkXml::ckDispose(xml)
                CkHashtable::ckDispose(seenTokens)
                ProcedureReturn
            EndIf

            ;  Replace the prior token; do not accumulate duplicate NextToken parameters.
            If page > 1
                success = CkRest::ckRemoveQueryParam(rest,"NextToken")
                If success <> 1
                    Debug "Could not remove the previous pagination token."
                    CkJsonObject::ckDispose(credentials)
                    CkStringBuilder::ckDispose(endpoint)
                    CkAuthAws::ckDispose(aws)
                    CkRest::ckDispose(rest)
                    CkSocket::ckDispose(connection)
                    CkXml::ckDispose(xml)
                    CkHashtable::ckDispose(seenTokens)
                    ProcedureReturn
                EndIf

            EndIf

            success = CkRest::ckAddQueryParam(rest,"NextToken",nextToken)
            If success <> 1
                Debug "Could not set NextToken."
                CkJsonObject::ckDispose(credentials)
                CkStringBuilder::ckDispose(endpoint)
                CkAuthAws::ckDispose(aws)
                CkRest::ckDispose(rest)
                CkSocket::ckDispose(connection)
                CkXml::ckDispose(xml)
                CkHashtable::ckDispose(seenTokens)
                ProcedureReturn
            EndIf

            more = 1
        EndIf

    Wend
    Debug "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.


    CkJsonObject::ckDispose(credentials)
    CkStringBuilder::ckDispose(endpoint)
    CkAuthAws::ckDispose(aws)
    CkRest::ckDispose(rest)
    CkSocket::ckDispose(connection)
    CkXml::ckDispose(xml)
    CkHashtable::ckDispose(seenTokens)


    ProcedureReturn
EndProcedure