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

Amazon EC2: Launch an Instance with a Persisted Idempotency Token

See more Amazon EC2 Examples

Live mode creates a billable instance. Before the first run, select an AMI compatible with the instance type, a subnet, a security group in that subnet's VPC, and an existing key pair, all in the chosen region. The sample requires IMDSv2. Public addressing follows the subnet configuration; this is not a promise of Internet reachability.

The private ec2-launch-request.json stores the region, exact illustrated parameters, and client token before submission, and the resulting instance ID after success. Reruns load the saved parameters; changing constants in the source does not change an existing request. Serialize access to this file and retain it after timeouts. Deliberate retries must use the same token and unchanged parameters in the same region/subnet; a different Availability Zone can create another instance. Reconcile uncertain outcomes by client token before creating a new intent. A recorded instance ID prevents this sample from resubmitting. Launch is asynchronous; use Wait for Instance State and Health Checks.

Dry run by default: change dryRun to false deliberately for the live operation. DryRunOperation means the permission check passed, not that a resource was changed or that the later operation is guaranteed to succeed. The example never automatically changes a dry run into a live 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:RunInstances. 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.

RunInstances 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 errorCode = ""
local dryRun = true
-- Serialize access to this private file. Use a new file only for a NEW intended launch.
local launchFile = "ec2-launch-request.json"
local files = chilkat.FileAccess.new()
local launch = chilkat.JsonObject.new()
launch.strict = true
local fileStatus = files:file_exists3(launchFile)
if fileStatus == 0 then
    -- Replace these sample settings before the first run. Later runs use the saved file.
    local uuid = chilkat.Crypt2.new()
    local clientToken = uuid:generate_uuid()
    local tokenText = chilkat.StringBuilder.new()
    tokenText:append(clientToken)
    if tokenText.length ~= 36 then
        print("Could not generate a launch token.")
        return
    end

    success = launch:update_string("client_token", clientToken)
    if not success then
        print("Could not save client token.")
        return
    end

    success = launch:update_string("region", region)
    if not success then
        print("Could not save region.")
        return
    end

    success = launch:update_string("image_id", "ami-0123456789abcdef0")
    if not success then
        print("Could not prepare image_id.")
        return
    end

    success = launch:update_string("instance_type", "t3.micro")
    if not success then
        print("Could not prepare instance_type.")
        return
    end

    success = launch:update_string("subnet_id", "subnet-0123456789abcdef0")
    if not success then
        print("Could not prepare subnet_id.")
        return
    end

    success = launch:update_string("security_group_id", "sg-0123456789abcdef0")
    if not success then
        print("Could not prepare security_group_id.")
        return
    end

    success = launch:update_string("key_name", "my-key-pair")
    if not success then
        print("Could not prepare key_name.")
        return
    end

    success = launch:update_string("min_count", "1")
    if not success then
        print("Could not prepare min_count.")
        return
    end

    success = launch:update_string("max_count", "1")
    if not success then
        print("Could not prepare max_count.")
        return
    end

    success = launch:update_string("http_tokens", "required")
    if not success then
        print("Could not prepare http_tokens.")
        return
    end

    success = launch:update_string("http_endpoint", "enabled")
    if not success then
        print("Could not prepare http_endpoint.")
        return
    end
else
    if fileStatus ~= 1 then
        print("Launch path is inaccessible or is not a regular file.")
        return
    end

    success = launch:load_file(launchFile)
    if not success then
        print("Could not load the saved launch request.")
        return
    end
end

if (launch:json_type_of("region") ~= 1) or (launch:string_of("region") == "") then
    print("Missing or invalid saved region.")
    return
end

if (launch:json_type_of("client_token") ~= 1) or (launch:string_of("client_token") == "") then
    print("Missing or invalid saved client_token.")
    return
end

if (launch:json_type_of("image_id") ~= 1) or (launch:string_of("image_id") == "") then
    print("Missing or invalid saved image_id.")
    return
end

if (launch:json_type_of("instance_type") ~= 1) or (launch:string_of("instance_type") == "") then
    print("Missing or invalid saved instance_type.")
    return
end

if (launch:json_type_of("subnet_id") ~= 1) or (launch:string_of("subnet_id") == "") then
    print("Missing or invalid saved subnet_id.")
    return
end

if (launch:json_type_of("security_group_id") ~= 1) or (launch:string_of("security_group_id") == "") then
    print("Missing or invalid saved security_group_id.")
    return
end

if (launch:json_type_of("key_name") ~= 1) or (launch:string_of("key_name") == "") then
    print("Missing or invalid saved key_name.")
    return
end

if (launch:json_type_of("min_count") ~= 1) or (launch:string_of("min_count") == "") then
    print("Missing or invalid saved min_count.")
    return
end

if (launch:json_type_of("max_count") ~= 1) or (launch:string_of("max_count") == "") then
    print("Missing or invalid saved max_count.")
    return
end

if (launch:json_type_of("http_tokens") ~= 1) or (launch:string_of("http_tokens") == "") then
    print("Missing or invalid saved http_tokens.")
    return
end

if (launch:json_type_of("http_endpoint") ~= 1) or (launch:string_of("http_endpoint") == "") then
    print("Missing or invalid saved http_endpoint.")
    return
end

if launch:string_of("region") ~= region then
    print("Saved launch region differs; do not reuse this token in another region.")
    return
end

if (launch:string_of("min_count") ~= "1") or (launch:string_of("max_count") ~= "1") then
    print("This demonstration launches exactly one instance.")
    return
end

if launch:has_member("instance_id") then
    if (launch:json_type_of("instance_id") ~= 1) or (launch:string_of("instance_id") == "") then
        print("Missing or invalid saved instance_id.")
        return
    end

    print("Launch already recorded for instance: " .. launch:string_of("instance_id"))
    print("No new launch request was sent.")
    return
end

-- Persist before sending, including dry runs. Never generate a new token for a retry.
success = launch:write_file(launchFile)
if not success then
    print("Could not persist launch parameters; no launch sent.")
    return
end

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

success = rest:add_query_param("ClientToken", launch:string_of("client_token"))
if not success then
    print("Could not set ClientToken.")
    return
end

success = rest:add_query_param("ImageId", launch:string_of("image_id"))
if not success then
    print("Could not set ImageId.")
    return
end

success = rest:add_query_param("InstanceType", launch:string_of("instance_type"))
if not success then
    print("Could not set InstanceType.")
    return
end

success = rest:add_query_param("SubnetId", launch:string_of("subnet_id"))
if not success then
    print("Could not set SubnetId.")
    return
end

success = rest:add_query_param("SecurityGroupId.1", launch:string_of("security_group_id"))
if not success then
    print("Could not set SecurityGroupId.1.")
    return
end

success = rest:add_query_param("KeyName", launch:string_of("key_name"))
if not success then
    print("Could not set KeyName.")
    return
end

success = rest:add_query_param("MinCount", launch:string_of("min_count"))
if not success then
    print("Could not set MinCount.")
    return
end

success = rest:add_query_param("MaxCount", launch:string_of("max_count"))
if not success then
    print("Could not set MaxCount.")
    return
end

success = rest:add_query_param("MetadataOptions.HttpTokens", launch:string_of("http_tokens"))
if not success then
    print("Could not set MetadataOptions.HttpTokens.")
    return
end

success = rest:add_query_param("MetadataOptions.HttpEndpoint", launch:string_of("http_endpoint"))
if not success then
    print("Could not set MetadataOptions.HttpEndpoint.")
    return
end

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

local responseXml = rest:full_request_no_body("GET", "/")
if not rest.last_method_success then
    print("Request did not complete; inspect diagnostics privately.")
    -- The operation might already have been accepted. Check state before retrying.
    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
            errorCode = xml:get_child_content("Errors|Error|Code")
            if (dryRun) and (errorCode == "DryRunOperation") then
                print("Dry run authorized. No resource was changed.")
                print("Set dryRun to false only when ready to perform the operation.")
                return
            end

            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 ~= "RunInstancesResponse" then
    print("Unexpected EC2 response element.")
    return
end

if dryRun then
    print("Unexpected HTTP 200 for a dry run; do not treat this as authorization to proceed.")
    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 xml:num_children_at("instancesSet") ~= 1 then
    print("Expected exactly one launched instance; reconcile using the saved client token.")
    return
end

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

local instanceId = xml:get_child_content("instancesSet|item|instanceId")
print("Launch accepted for instance: " .. instanceId)
if xml:has_child_with_tag("instancesSet|item|instanceState|name") then
    print("State: " .. xml:get_child_content("instancesSet|item|instanceState|name"))
end

success = launch:update_string("instance_id", instanceId)
if not success then
    print("Could not record the returned instance ID; keep it privately.")
    return
end

success = launch:write_file(launchFile)
if not success then
    print("Launch accepted but the result could not be saved. Record the ID before retrying.")
    return
end

print("Saved instance ID. Wait for running state and health before use.")