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

Lua
local chilkat = require("chilkat")

-- Assumes Chilkat is unlocked. See Global Unlock Sample.
-- Private configuration, not a file in public web content or source control.
-- Load current IAM credentials authorized for the EC2 operation.
local credentials = chilkat.JsonObject.new()
credentials.strict = true
local success = credentials:load_file("qa_data/aws/ec2.json")
if not success then
    print("Could not load private AWS credentials.")
    return
end

if (credentials:json_type_of("access_key") ~= 1) or (credentials:string_of("access_key") == "") then
    print("Missing or invalid access_key.")
    return
end

if (credentials:json_type_of("secret_key") ~= 1) or (credentials:string_of("secret_key") == "") then
    print("Missing or invalid secret_key.")
    return
end

-- Set this once to the region containing the instances.
local region = "us-west-2"
local endpoint = chilkat.StringBuilder.new()
endpoint:append("ec2.")
endpoint:append(region)
endpoint:append(".amazonaws.com")
local aws = chilkat.AuthAws.new()
aws.access_key = credentials:string_of("access_key")
aws.secret_key = credentials:string_of("secret_key")
aws.region = region
aws.service_name = "ec2"
aws.signature_version = 4
local rest = chilkat.Rest.new()
rest.connect_timeout_ms = 20000
rest.idle_timeout_ms = 60000
success = rest:set_auth_aws(aws)
if not success then
    print("Could not configure AWS signing.")
    return
end

-- 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:has_member("session_token") then
    if credentials:json_type_of("session_token") ~= 1 then
        print("session_token must be a string.")
        return
    end

    if credentials:string_of("session_token") ~= "" then
        success = rest:add_query_param("X-Amz-Security-Token", credentials:string_of("session_token"))
        if not success then
            print("Could not set the session-token parameter.")
            return
        end
    end
end

-- Supply a Socket to explicitly enable TLS certificate verification.
local connection = chilkat.Socket.new()
connection.require_ssl_cert_verify = true
connection.max_read_idle_ms = 60000
connection.max_send_idle_ms = 60000
success = connection:connect(endpoint:get_as_string(), 443, true, 20000)
if not success then
    print("TLS connection failed; inspect diagnostics privately.")
    return
end

success = rest:use_connection(connection, true)
if not success then
    print("Could not attach the TLS connection.")
    return
end

-- 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.
local xml = chilkat.Xml.new()
xml.strict = true
success = rest:add_query_param("Version", "2016-11-15")
if not success then
    print("Could not set Version.")
    return
end

success = rest:add_query_param("Action", "DescribeInstanceStatus")
if not success then
    print("Could not set Action.")
    return
end

-- Include stopped and other non-running instances as well as running instances.
-- This flag does NOT override InstanceId.N filters.
success = rest:add_query_param("IncludeAllInstances", "true")
if not success then
    print("Could not set IncludeAllInstances.")
    return
end

success = rest:add_query_param("MaxResults", "100")
if not success then
    print("Could not set MaxResults.")
    return
end

-- 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.
local seenTokens = chilkat.Hashtable.new()
local nextToken = ""
local more = true
local page = 0
while more do
    if page == 1000 then
        print("Stopped at 1000 pages; status enumeration is incomplete.")
        -- Save nextToken privately to resume. It is not a permanent checkpoint.
        return
    end

    local responseXml = rest:full_request_no_body("GET", "/")
    if not rest.last_method_success then
        print("Request did not complete; inspect diagnostics privately.")
        return
    end

    success = xml:load_xml(responseXml)
    if rest.response_status_code ~= 200 then
        print("EC2 HTTP status: " .. rest.response_status_code)
        if success then
            if xml:has_child_with_tag("Errors|Error|Code") then
                local errorCode = xml:get_child_content("Errors|Error|Code")
                print("AWS error code: " .. errorCode)
            end

            if xml:has_child_with_tag("RequestID") then
                print("AWS request ID: " .. xml:get_child_content("RequestID"))
            end
        end

        -- 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.
        return
    end

    if not success then
        print("Expected a well-formed XML response.")
        return
    end

    if xml.tag ~= "DescribeInstanceStatusResponse" then
        print("Unexpected EC2 response element.")
        return
    end

    if (not xml:has_child_with_tag("requestId")) or (xml:get_child_content("requestId") == "") then
        print("Missing or empty requestId.")
        return
    end

    print("AWS request ID: " .. xml:get_child_content("requestId"))
    if not xml:has_child_with_tag("instanceStatusSet") then
        print("Expected instanceStatusSet.")
        return
    end

    local i = 0
    while i < xml:num_children_at("instanceStatusSet") do
        xml.i = i
        if (not xml:has_child_with_tag("instanceStatusSet|item[i]|instanceId")) or (xml:get_child_content("instanceStatusSet|item[i]|instanceId") == "") then
            print("Missing or empty instanceStatusSet|item[i]|instanceId.")
            return
        end

        print("Instance: " .. xml:get_child_content("instanceStatusSet|item[i]|instanceId"))
        -- Read by element name; XML response element order is not guaranteed.
        if xml:has_child_with_tag("instanceStatusSet|item[i]|availabilityZone") then
            print("Availability Zone: " .. xml:get_child_content("instanceStatusSet|item[i]|availabilityZone"))
        end

        if xml:has_child_with_tag("instanceStatusSet|item[i]|instanceState|name") then
            print("State: " .. xml:get_child_content("instanceStatusSet|item[i]|instanceState|name"))
        end

        if xml:has_child_with_tag("instanceStatusSet|item[i]|systemStatus|status") then
            print("System health: " .. xml:get_child_content("instanceStatusSet|item[i]|systemStatus|status"))
        end

        if xml:has_child_with_tag("instanceStatusSet|item[i]|instanceStatus|status") then
            print("Instance health: " .. xml:get_child_content("instanceStatusSet|item[i]|instanceStatus|status"))
        end

        if xml:has_child_with_tag("instanceStatusSet|item[i]|attachedEbsStatus|status") then
            print("Attached EBS health: " .. xml:get_child_content("instanceStatusSet|item[i]|attachedEbsStatus|status"))
        end

        if xml:has_child_with_tag("instanceStatusSet|item[i]|applicationStatus|status") then
            print("Application health: " .. xml:get_child_content("instanceStatusSet|item[i]|applicationStatus|status"))
        end

        if xml:has_child_with_tag("instanceStatusSet|item[i]|performanceStatus|status") then
            print("Performance health: " .. xml:get_child_content("instanceStatusSet|item[i]|performanceStatus|status"))
        end

        -- Scheduled events may be absent. Event IDs and timestamps remain strings.
        local j = 0
        while j < xml:num_children_at("instanceStatusSet|item[i]|eventsSet") do
            xml.j = j
            if xml:has_child_with_tag("instanceStatusSet|item[i]|eventsSet|item[j]|instanceEventId") then
                print("Event ID: " .. xml:get_child_content("instanceStatusSet|item[i]|eventsSet|item[j]|instanceEventId"))
            end

            if xml:has_child_with_tag("instanceStatusSet|item[i]|eventsSet|item[j]|code") then
                print("Event: " .. xml:get_child_content("instanceStatusSet|item[i]|eventsSet|item[j]|code"))
            end

            if xml:has_child_with_tag("instanceStatusSet|item[i]|eventsSet|item[j]|description") then
                print("Description: " .. xml:get_child_content("instanceStatusSet|item[i]|eventsSet|item[j]|description"))
            end

            if xml:has_child_with_tag("instanceStatusSet|item[i]|eventsSet|item[j]|notBefore") then
                print("Not before: " .. xml:get_child_content("instanceStatusSet|item[i]|eventsSet|item[j]|notBefore"))
            end

            if xml:has_child_with_tag("instanceStatusSet|item[i]|eventsSet|item[j]|notAfter") then
                print("Not after: " .. xml:get_child_content("instanceStatusSet|item[i]|eventsSet|item[j]|notAfter"))
            end

            if xml:has_child_with_tag("instanceStatusSet|item[i]|eventsSet|item[j]|notBeforeDeadline") then
                print("Rescheduling deadline: " .. xml:get_child_content("instanceStatusSet|item[i]|eventsSet|item[j]|notBeforeDeadline"))
            end

            j = j + 1
        end

        i = i + 1
    end

    page = page + 1
    more = false
    nextToken = ""
    if xml:has_child_with_tag("nextToken") then
        nextToken = xml:get_child_content("nextToken")
    end

    if nextToken ~= "" then
        if seenTokens:contains(nextToken) then
            print("Repeated pagination token; status enumeration is incomplete.")
            return
        end

        success = seenTokens:add_int(nextToken, 1)
        if not success then
            print("Could not track pagination.")
            return
        end

        -- Replace the prior token; do not accumulate duplicate NextToken parameters.
        if page > 1 then
            success = rest:remove_query_param("NextToken")
            if not success then
                print("Could not remove the previous pagination token.")
                return
            end
        end

        success = rest:add_query_param("NextToken", nextToken)
        if not success then
            print("Could not set NextToken.")
            return
        end

        more = true
    end
end

print("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.