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

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoCredentials
    String sRegion
    Handle hoEndpoint
    Variant vAws
    Handle hoAws
    Handle hoRest
    Variant vConnection
    Handle hoConnection
    Handle hoXml
    String sResponseXml
    String sErrorCode
    String sVolumeId
    Boolean iDryRun
    String sCheckpointFile
    Handle hoFiles
    Handle hoCheckpoint
    String sSnapshotId
    Integer iFileStatus
    Handle hoStarted
    String sState
    Integer iAttempt
    Integer iDelayMs
    Boolean iRetryRead
    String sTemp1
    String sTemp2
    Integer iTemp1
    Boolean bTemp1

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    Move False To iSuccess
    //  Private configuration, not a file in public web content or source control.
    //  Load current IAM credentials authorized for the EC2 operation.
    Get Create (RefClass(cComChilkatJsonObject)) To hoCredentials
    If (Not(IsComObjectCreated(hoCredentials))) Begin
        Send CreateComObject of hoCredentials
    End
    Set ComStrict Of hoCredentials To True
    Get ComLoadFile Of hoCredentials "qa_data/aws/ec2.json" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not load private AWS credentials."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoCredentials "access_key" To iTemp1
    Get ComStringOf Of hoCredentials "access_key" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid access_key."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoCredentials "secret_key" To iTemp1
    Get ComStringOf Of hoCredentials "secret_key" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid secret_key."
        Procedure_Return
    End

    //  Set this once to the region containing the instances.
    Move "us-west-2" To sRegion
    Get Create (RefClass(cComChilkatStringBuilder)) To hoEndpoint
    If (Not(IsComObjectCreated(hoEndpoint))) Begin
        Send CreateComObject of hoEndpoint
    End
    Get ComAppend Of hoEndpoint "ec2." To iSuccess
    Get ComAppend Of hoEndpoint sRegion To iSuccess
    Get ComAppend Of hoEndpoint ".amazonaws.com" To iSuccess
    Get Create (RefClass(cComChilkatAuthAws)) To hoAws
    If (Not(IsComObjectCreated(hoAws))) Begin
        Send CreateComObject of hoAws
    End
    Get ComStringOf Of hoCredentials "access_key" To sTemp1
    Set ComAccessKey Of hoAws To sTemp1
    Get ComStringOf Of hoCredentials "secret_key" To sTemp1
    Set ComSecretKey Of hoAws To sTemp1
    Set ComRegion Of hoAws To sRegion
    Set ComServiceName Of hoAws To "ec2"
    Set ComSignatureVersion Of hoAws To 4
    Get Create (RefClass(cComChilkatRest)) To hoRest
    If (Not(IsComObjectCreated(hoRest))) Begin
        Send CreateComObject of hoRest
    End
    Set ComConnectTimeoutMs Of hoRest To 20000
    Set ComIdleTimeoutMs Of hoRest To 60000
    Get pvComObject of hoAws to vAws
    Get ComSetAuthAws Of hoRest vAws To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not configure AWS signing."
        Procedure_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.
    Get ComHasMember Of hoCredentials "session_token" To bTemp1
    If (bTemp1 = True) Begin
        Get ComJsonTypeOf Of hoCredentials "session_token" To iTemp1
        If (iTemp1 <> 1) Begin
            Showln "session_token must be a string."
            Procedure_Return
        End

        Get ComStringOf Of hoCredentials "session_token" To sTemp1
        If (sTemp1 <> "") Begin
            Get ComStringOf Of hoCredentials "session_token" To sTemp1
            Get ComAddQueryParam Of hoRest "X-Amz-Security-Token" sTemp1 To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not set the session-token parameter."
                Procedure_Return
            End

        End

    End

    //  Supply a Socket to explicitly enable TLS certificate verification.
    Get Create (RefClass(cComChilkatSocket)) To hoConnection
    If (Not(IsComObjectCreated(hoConnection))) Begin
        Send CreateComObject of hoConnection
    End
    Set ComRequireSslCertVerify Of hoConnection To True
    Set ComMaxReadIdleMs Of hoConnection To 60000
    Set ComMaxSendIdleMs Of hoConnection To 60000
    Get ComGetAsString Of hoEndpoint To sTemp1
    Get ComConnect Of hoConnection sTemp1 443 True 20000 To iSuccess
    If (iSuccess <> True) Begin
        Showln "TLS connection failed; inspect diagnostics privately."
        Procedure_Return
    End

    Get pvComObject of hoConnection to vConnection
    Get ComUseConnection Of hoRest vConnection True To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not attach the TLS connection."
        Procedure_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.
    Get Create (RefClass(cComChilkatXml)) To hoXml
    If (Not(IsComObjectCreated(hoXml))) Begin
        Send CreateComObject of hoXml
    End
    Set ComStrict Of hoXml To True
    Get ComAddQueryParam Of hoRest "Version" "2016-11-15" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set Version."
        Procedure_Return
    End

    Move "" To sResponseXml
    Move "" To sErrorCode
    Move "vol-0123456789abcdef0" To sVolumeId
    Move True To iDryRun
    //  Serialize access. Keep this checkpoint after any uncertain create response.
    Move "ec2-snapshot-request.json" To sCheckpointFile
    Get Create (RefClass(cComCkFileAccess)) To hoFiles
    If (Not(IsComObjectCreated(hoFiles))) Begin
        Send CreateComObject of hoFiles
    End
    Get Create (RefClass(cComChilkatJsonObject)) To hoCheckpoint
    If (Not(IsComObjectCreated(hoCheckpoint))) Begin
        Send CreateComObject of hoCheckpoint
    End
    Set ComStrict Of hoCheckpoint To True
    Move "" To sSnapshotId
    Get ComFileExists3 Of hoFiles sCheckpointFile To iFileStatus
    If (iFileStatus <> 0) Begin
        If (iFileStatus <> 1) Begin
            Showln "Snapshot checkpoint path is inaccessible or is not a file."
            Procedure_Return
        End

        Get ComLoadFile Of hoCheckpoint sCheckpointFile To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not read snapshot checkpoint."
            Procedure_Return
        End

        Get ComJsonTypeOf Of hoCheckpoint "region" To iTemp1
        Get ComStringOf Of hoCheckpoint "region" To sTemp1
        If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
            Showln "Missing or invalid saved region."
            Procedure_Return
        End

        Get ComJsonTypeOf Of hoCheckpoint "volume_id" To iTemp1
        Get ComStringOf Of hoCheckpoint "volume_id" To sTemp1
        If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
            Showln "Missing or invalid saved volume_id."
            Procedure_Return
        End

        Get ComStringOf Of hoCheckpoint "region" To sTemp1
        Get ComStringOf Of hoCheckpoint "volume_id" To sTemp2
        If ((sTemp1 <> sRegion) Or (sTemp2 <> sVolumeId)) Begin
            Showln "Checkpoint belongs to another region or volume."
            Procedure_Return
        End

        Get ComHasMember Of hoCheckpoint "snapshot_id" To bTemp1
        If (bTemp1 <> True) Begin
            Showln "An earlier create outcome is uncertain. Reconcile it before another CreateSnapshot."
            Procedure_Return
        End

        Get ComJsonTypeOf Of hoCheckpoint "snapshot_id" To iTemp1
        Get ComStringOf Of hoCheckpoint "snapshot_id" To sTemp1
        If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
            Showln "Missing or invalid saved snapshot_id."
            Procedure_Return
        End

        Get ComStringOf Of hoCheckpoint "snapshot_id" To sSnapshotId
        Showln "Resuming read-only status checks for " sSnapshotId
    End

    If (sSnapshotId = "") Begin
        If (iDryRun = False) Begin
            Get Create (RefClass(cComCkDateTime)) To hoStarted
            If (Not(IsComObjectCreated(hoStarted))) Begin
                Send CreateComObject of hoStarted
            End
            Get ComSetFromCurrentSystemTime Of hoStarted To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not read the current time."
                Procedure_Return
            End

            Get ComUpdateString Of hoCheckpoint "region" sRegion To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not record region."
                Procedure_Return
            End

            Get ComUpdateString Of hoCheckpoint "volume_id" sVolumeId To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not record volume."
                Procedure_Return
            End

            Get ComGetAsTimestamp Of hoStarted False To sTemp1
            Get ComUpdateString Of hoCheckpoint "requested_at" sTemp1 To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not record request time."
                Procedure_Return
            End

            Get ComWriteFile Of hoCheckpoint sCheckpointFile To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not persist create intent; no snapshot request sent."
                Procedure_Return
            End

        End

        Get ComAddQueryParam Of hoRest "Action" "CreateSnapshot" To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not set Action."
            Procedure_Return
        End

        Get ComAddQueryParam Of hoRest "VolumeId" sVolumeId To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not set VolumeId."
            Procedure_Return
        End

        Get ComAddQueryParam Of hoRest "Description" "Example volume snapshot" To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not set Description."
            Procedure_Return
        End

        If (iDryRun = True) Begin
            Get ComAddQueryParam Of hoRest "DryRun" "true" To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not set DryRun."
                Procedure_Return
            End

        End

        Get ComFullRequestNoBody Of hoRest "GET" "/" To sResponseXml
        Get ComLastMethodSuccess Of hoRest To bTemp1
        If (bTemp1 <> True) Begin
            Showln "Request did not complete; inspect diagnostics privately."
            //  The operation might already have been accepted. Check state before retrying.
            Procedure_Return
        End

        Get ComLoadXml Of hoXml sResponseXml To iSuccess
        Get ComResponseStatusCode Of hoRest To iTemp1
        If (iTemp1 <> 200) Begin
            Get ComResponseStatusCode Of hoRest To iTemp1
            Showln "EC2 HTTP status: " iTemp1
            If (iSuccess = True) Begin
                Get ComHasChildWithTag Of hoXml "Errors|Error|Code" To bTemp1
                If (bTemp1 = True) Begin
                    Get ComGetChildContent Of hoXml "Errors|Error|Code" To sErrorCode
                    If ((iDryRun = True) And (sErrorCode = "DryRunOperation")) Begin
                        Showln "Dry run authorized. No resource was changed."
                        Showln "Set dryRun to false only when ready to perform the operation."
                        Procedure_Return
                    End

                    Showln "AWS error code: " sErrorCode
                End

                Get ComHasChildWithTag Of hoXml "RequestID" To bTemp1
                If (bTemp1 = True) Begin
                    Get ComGetChildContent Of hoXml "RequestID" To sTemp1
                    Showln "AWS request ID: " sTemp1
                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.
            Procedure_Return
        End

        If (iSuccess <> True) Begin
            Showln "Expected a well-formed XML response."
            Procedure_Return
        End

        Get ComTag Of hoXml To sTemp1
        If (sTemp1 <> "CreateSnapshotResponse") Begin
            Showln "Unexpected EC2 response element."
            Procedure_Return
        End

        If (iDryRun = True) Begin
            Showln "Unexpected HTTP 200 for a dry run; do not treat this as authorization to proceed."
            Procedure_Return
        End

        Get ComHasChildWithTag Of hoXml "requestId" To bTemp1
        Get ComGetChildContent Of hoXml "requestId" To sTemp1
        If ((bTemp1 <> True) Or (sTemp1 = "")) Begin
            Showln "Missing or empty requestId."
            Procedure_Return
        End

        Get ComGetChildContent Of hoXml "requestId" To sTemp1
        Showln "AWS request ID: " sTemp1
        Get ComHasChildWithTag Of hoXml "snapshotId" To bTemp1
        Get ComGetChildContent Of hoXml "snapshotId" To sTemp1
        If ((bTemp1 <> True) Or (sTemp1 = "")) Begin
            Showln "Missing or empty snapshotId."
            Procedure_Return
        End

        Get ComGetChildContent Of hoXml "snapshotId" To sSnapshotId
        Showln "Snapshot creation accepted: " sSnapshotId
        Get ComUpdateString Of hoCheckpoint "snapshot_id" sSnapshotId To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not record snapshot ID; save the displayed ID privately."
            Procedure_Return
        End

        Get ComWriteFile Of hoCheckpoint sCheckpointFile To iSuccess
        If (iSuccess <> True) Begin
            Showln "Snapshot accepted but checkpoint save failed; record the ID before continuing."
            Procedure_Return
        End

        Get ComRemoveQueryParam Of hoRest "Action" To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not change action."
            Procedure_Return
        End

        Get ComRemoveQueryParam Of hoRest "VolumeId" To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not remove create parameter."
            Procedure_Return
        End

        Get ComRemoveQueryParam Of hoRest "Description" To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not remove description."
            Procedure_Return
        End

    End

    //  Keep the signed session token and Version; remove only the prior action's parameters.
    Get ComAddQueryParam Of hoRest "Action" "DescribeSnapshots" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set Action."
        Procedure_Return
    End

    Get ComAddQueryParam Of hoRest "SnapshotId.1" sSnapshotId To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set SnapshotId.1."
        Procedure_Return
    End

    Move "" To sState
    //  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.
    Move 0 To iAttempt
    Move 2000 To iDelayMs
    Move False To iRetryRead
    While (iAttempt < 60)
        Move False To iRetryRead
        Get ComFullRequestNoBody Of hoRest "GET" "/" To sResponseXml
        Get ComLastMethodSuccess Of hoRest To bTemp1
        If (bTemp1 <> True) Begin
            Showln "Polling transport failed; resume the read later. No write was retried."
            Procedure_Return
        End

        Get ComLoadXml Of hoXml sResponseXml To iSuccess
        Get ComResponseStatusCode Of hoRest To iTemp1
        If (iTemp1 <> 200) Begin
            Move "" To sErrorCode
            If (iSuccess = True) Begin
                Get ComHasChildWithTag Of hoXml "Errors|Error|Code" To bTemp1
                If (bTemp1 = True) Begin
                    Get ComGetChildContent Of hoXml "Errors|Error|Code" To sErrorCode
                End

            End

            If ((sErrorCode = "RequestLimitExceeded") Or (sErrorCode = "InternalError") Or (sErrorCode = "ServiceUnavailable") Or (sErrorCode = "InvalidSnapshot.NotFound")) Begin
                Move True To iRetryRead
            End
            Else Begin
                Get ComResponseStatusCode Of hoRest To iTemp1
                Showln "Polling failed: HTTP " iTemp1 "; AWS code: " sErrorCode
                Procedure_Return
            End

        End

        If (iRetryRead = False) Begin
            If (iSuccess <> True) Begin
                Showln "Expected a well-formed XML response."
                Procedure_Return
            End

            Get ComTag Of hoXml To sTemp1
            If (sTemp1 <> "DescribeSnapshotsResponse") Begin
                Showln "Unexpected polling response."
                Procedure_Return
            End

            Get ComHasChildWithTag Of hoXml "requestId" To bTemp1
            Get ComGetChildContent Of hoXml "requestId" To sTemp1
            If ((bTemp1 <> True) Or (sTemp1 = "")) Begin
                Showln "Missing or empty requestId."
                Procedure_Return
            End

            Get ComHasChildWithTag Of hoXml "snapshotSet" To bTemp1
            If (bTemp1 <> True) Begin
                Showln "Expected snapshotSet."
                Procedure_Return
            End

            Get ComNumChildrenAt Of hoXml "snapshotSet" To iTemp1
            If (iTemp1 > 0) Begin
                Get ComNumChildrenAt Of hoXml "snapshotSet" To iTemp1
                If (iTemp1 <> 1) Begin
                    Showln "Expected one snapshot."
                    Procedure_Return
                End

                Get ComHasChildWithTag Of hoXml "snapshotSet|item|snapshotId" To bTemp1
                Get ComGetChildContent Of hoXml "snapshotSet|item|snapshotId" To sTemp1
                If ((bTemp1 <> True) Or (sTemp1 = "")) Begin
                    Showln "Missing or empty snapshotSet|item|snapshotId."
                    Procedure_Return
                End

                Get ComGetChildContent Of hoXml "snapshotSet|item|snapshotId" To sTemp1
                If (sTemp1 <> sSnapshotId) Begin
                    Showln "Unexpected snapshot ID."
                    Procedure_Return
                End

                Get ComHasChildWithTag Of hoXml "snapshotSet|item|status" To bTemp1
                Get ComGetChildContent Of hoXml "snapshotSet|item|status" To sTemp1
                If ((bTemp1 <> True) Or (sTemp1 = "")) Begin
                    Showln "Missing or empty snapshotSet|item|status."
                    Procedure_Return
                End

                Get ComGetChildContent Of hoXml "snapshotSet|item|status" To sState
                Showln "Snapshot state: " sState
                Get ComHasChildWithTag Of hoXml "snapshotSet|item|progress" To bTemp1
                If (bTemp1 = True) Begin
                    Get ComGetChildContent Of hoXml "snapshotSet|item|progress" To sTemp1
                    Showln "Progress: " sTemp1
                End

                If (sState = "completed") Begin
                    Showln "Snapshot completed: " sSnapshotId
                    Procedure_Return
                End

                If (sState = "error") Begin
                    Showln "Snapshot entered error state. Inspect details privately; do not create another automatically."
                    Procedure_Return
                End

            End

        End

        Move (iAttempt + 1) To iAttempt
        If (iAttempt < 60) Begin
            Send ComSleepMs To hoConnection iDelayMs
            If (iDelayMs < 10000) Begin
                Move (iDelayMs * 2) To iDelayMs
                If (iDelayMs > 10000) Begin
                    Move 10000 To iDelayMs
                End

            End

        End

    Loop

    Showln "Polling limit reached; completion has not been confirmed. Resume checking later."


End_Procedure