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

Amazon EC2: Create an EBS Snapshot and Monitor Completion

See more Amazon EC2 Examples

Live mode creates a billable snapshot. This is a single-volume backup, not an application-consistent multi-volume backup. Quiesce application writes and flush buffers as appropriate before the create request; cached data is not captured. For a root volume, stopping the instance first is recommended. Encryption follows the source volume; KMS access may be required.

The private checkpoint records region, volume, and request time before creation, then the returned snapshot ID. An existing ID resumes read-only polling, even with dryRun=true. A checkpoint without an ID stops for reconciliation: CreateSnapshot has no client token, so blindly repeating an uncertain create could produce another snapshot. Keep the checkpoint after timeouts. Polls up to 60 times with delays capped at 10 seconds and reports completion, error, or an unconfirmed timeout. This sample never deletes snapshots or resets the checkpoint automatically.

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:CreateSnapshot, ec2:DescribeSnapshots. 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.

CreateSnapshot reference, DescribeSnapshots 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 volumeId = "vol-0123456789abcdef0"
local dryRun = true
-- Serialize access. Keep this checkpoint after any uncertain create response.
local checkpointFile = "ec2-snapshot-request.json"
local files = chilkat.FileAccess.new()
local checkpoint = chilkat.JsonObject.new()
checkpoint.strict = true
local snapshotId = ""
local fileStatus = files:file_exists3(checkpointFile)
if fileStatus ~= 0 then
    if fileStatus ~= 1 then
        print("Snapshot checkpoint path is inaccessible or is not a file.")
        return
    end

    success = checkpoint:load_file(checkpointFile)
    if not success then
        print("Could not read snapshot checkpoint.")
        return
    end

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

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

    if (checkpoint:string_of("region") ~= region) or (checkpoint:string_of("volume_id") ~= volumeId) then
        print("Checkpoint belongs to another region or volume.")
        return
    end

    if not checkpoint:has_member("snapshot_id") then
        print("An earlier create outcome is uncertain. Reconcile it before another CreateSnapshot.")
        return
    end

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

    snapshotId = checkpoint:string_of("snapshot_id")
    print("Resuming read-only status checks for " .. snapshotId)
end

if snapshotId == "" then
    if not dryRun then
        local started = chilkat.DateTime.new()
        success = started:set_from_current_system_time()
        if not success then
            print("Could not read the current time.")
            return
        end

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

        success = checkpoint:update_string("volume_id", volumeId)
        if not success then
            print("Could not record volume.")
            return
        end

        success = checkpoint:update_string("requested_at", started:get_as_timestamp(false))
        if not success then
            print("Could not record request time.")
            return
        end

        success = checkpoint:write_file(checkpointFile)
        if not success then
            print("Could not persist create intent; no snapshot request sent.")
            return
        end
    end

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

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

    success = rest:add_query_param("Description", "Example volume snapshot")
    if not success then
        print("Could not set Description.")
        return
    end

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

    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 ~= "CreateSnapshotResponse" 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 (not xml:has_child_with_tag("snapshotId")) or (xml:get_child_content("snapshotId") == "") then
        print("Missing or empty snapshotId.")
        return
    end

    snapshotId = xml:get_child_content("snapshotId")
    print("Snapshot creation accepted: " .. snapshotId)
    success = checkpoint:update_string("snapshot_id", snapshotId)
    if not success then
        print("Could not record snapshot ID; save the displayed ID privately.")
        return
    end

    success = checkpoint:write_file(checkpointFile)
    if not success then
        print("Snapshot accepted but checkpoint save failed; record the ID before continuing.")
        return
    end

    success = rest:remove_query_param("Action")
    if not success then
        print("Could not change action.")
        return
    end

    success = rest:remove_query_param("VolumeId")
    if not success then
        print("Could not remove create parameter.")
        return
    end

    success = rest:remove_query_param("Description")
    if not success then
        print("Could not remove description.")
        return
    end
end

-- Keep the signed session token and Version; remove only the prior action's parameters.
success = rest:add_query_param("Action", "DescribeSnapshots")
if not success then
    print("Could not set Action.")
    return
end

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

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 == "InvalidSnapshot.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 ~= "DescribeSnapshotsResponse" 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("snapshotSet") then
            print("Expected snapshotSet.")
            return
        end

        if xml:num_children_at("snapshotSet") > 0 then
            if xml:num_children_at("snapshotSet") ~= 1 then
                print("Expected one snapshot.")
                return
            end

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

            if xml:get_child_content("snapshotSet|item|snapshotId") ~= snapshotId then
                print("Unexpected snapshot ID.")
                return
            end

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

            state = xml:get_child_content("snapshotSet|item|status")
            print("Snapshot state: " .. state)
            if xml:has_child_with_tag("snapshotSet|item|progress") then
                print("Progress: " .. xml:get_child_content("snapshotSet|item|progress"))
            end

            if state == "completed" then
                print("Snapshot completed: " .. snapshotId)
                return
            end

            if state == "error" then
                print("Snapshot entered error state. Inspect details privately; do not create another automatically.")
                return
            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.")