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

local responseXml = ""
local errorCode = ""
local instanceId = "i-1234567890abcdef0"
-- Supported goals: "running" (with health checks) or "stopped" (state only).
local desiredState = "running"
if (desiredState ~= "running") and (desiredState ~= "stopped") then
    print("Choose running or stopped.")
    return
end

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

success = rest:add_query_param("InstanceId.1", instanceId)
if not success then
    print("Could not set InstanceId.1.")
    return
end

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

-- No MaxResults with explicit IDs. A missing entry is not readiness.
local 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.
local attempt = 0
local delayMs = 2000
local retryRead = false
while attempt < 60 do
    retryRead = false
    responseXml = rest:full_request_no_body("GET", "/")
    if not rest.last_method_success then
        print("Polling transport failed; resume the read later. No write was retried.")
        return
    end

    success = xml:load_xml(responseXml)
    if rest.response_status_code ~= 200 then
        errorCode = ""
        if success then
            if xml:has_child_with_tag("Errors|Error|Code") then
                errorCode = xml:get_child_content("Errors|Error|Code")
            end
        end

        if (errorCode == "RequestLimitExceeded") or ((errorCode == "InternalError") or ((errorCode == "ServiceUnavailable") or (errorCode == "InvalidInstanceID.NotFound"))) then
            retryRead = true
        else
            print("Polling failed: HTTP " .. rest.response_status_code .. "; AWS code: " .. errorCode)
            return
        end
    end

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

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

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

        if not xml:has_child_with_tag("instanceStatusSet") then
            print("Expected instanceStatusSet.")
            return
        end

        if xml:num_children_at("instanceStatusSet") > 0 then
            if xml:num_children_at("instanceStatusSet") ~= 1 then
                print("Expected one instance status.")
                return
            end

            if (not xml:has_child_with_tag("instanceStatusSet|item|instanceId")) or (xml:get_child_content("instanceStatusSet|item|instanceId") == "") then
                print("Missing or empty instanceStatusSet|item|instanceId.")
                return
            end

            if xml:get_child_content("instanceStatusSet|item|instanceId") ~= instanceId then
                print("Unexpected instance ID.")
                return
            end

            if (not xml:has_child_with_tag("instanceStatusSet|item|instanceState|name")) or (xml:get_child_content("instanceStatusSet|item|instanceState|name") == "") then
                print("Missing or empty instanceStatusSet|item|instanceState|name.")
                return
            end

            state = xml:get_child_content("instanceStatusSet|item|instanceState|name")
            print("Observed state: " .. state)
            if (state == "shutting-down") or (state == "terminated") then
                print("Instance is terminating or terminated; requested readiness cannot be reached.")
                return
            end

            if state == desiredState then
                if desiredState == "stopped" then
                    print("Instance reached stopped state.")
                    return
                end

                -- Both statuses must explicitly be ok. Missing/initializing/impaired is not ready.
                if (xml:get_child_content("instanceStatusSet|item|systemStatus|status") == "ok") and (xml:get_child_content("instanceStatusSet|item|instanceStatus|status") == "ok") then
                    print("Instance is running and both EC2 health checks are ok.")
                    print("Check application readiness separately.")
                    return
                end
            end
        end
    end

    attempt = attempt + 1
    if attempt < 60 then
        connection:sleep_ms(delayMs)
        if delayMs < 10000 then
            delayMs = delayMs * 2
            if delayMs > 10000 then
                delayMs = 10000
            end
        end
    end
end

print("Polling limit reached; completion has not been confirmed. Resume checking later.")