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

Delphi DLL
var
success: Boolean;
credentials: HCkJsonObject;
region: PWideChar;
endpoint: HCkStringBuilder;
aws: HCkAuthAws;
rest: HCkRest;
connection: HCkSocket;
xml: HCkXml;
responseXml: PWideChar;
errorCode: PWideChar;
volumeId: PWideChar;
dryRun: Boolean;
checkpointFile: PWideChar;
files: HCkFileAccess;
checkpoint: HCkJsonObject;
snapshotId: PWideChar;
fileStatus: Integer;
started: HCkDateTime;
state: PWideChar;
attempt: Integer;
delayMs: Integer;
retryRead: Boolean;

begin
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
success := False;
//  Private configuration, not a file in public web content or source control.
//  Load current IAM credentials authorized for the EC2 operation.
credentials := CkJsonObject_Create();
CkJsonObject_putStrict(credentials,True);
success := CkJsonObject_LoadFile(credentials,'qa_data/aws/ec2.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load private AWS credentials.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(credentials,'access_key') <> 1) or (CkJsonObject__stringOf(credentials,'access_key') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid access_key.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(credentials,'secret_key') <> 1) or (CkJsonObject__stringOf(credentials,'secret_key') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid secret_key.');
    Exit;
  end;
//  Set this once to the region containing the instances.
region := 'us-west-2';
endpoint := CkStringBuilder_Create();
CkStringBuilder_Append(endpoint,'ec2.');
CkStringBuilder_Append(endpoint,region);
CkStringBuilder_Append(endpoint,'.amazonaws.com');
aws := CkAuthAws_Create();
CkAuthAws_putAccessKey(aws,CkJsonObject__stringOf(credentials,'access_key'));
CkAuthAws_putSecretKey(aws,CkJsonObject__stringOf(credentials,'secret_key'));
CkAuthAws_putRegion(aws,region);
CkAuthAws_putServiceName(aws,'ec2');
CkAuthAws_putSignatureVersion(aws,4);
rest := CkRest_Create();
CkRest_putConnectTimeoutMs(rest,20000);
CkRest_putIdleTimeoutMs(rest,60000);
success := CkRest_SetAuthAws(rest,aws);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not configure AWS signing.');
    Exit;
  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 (CkJsonObject_HasMember(credentials,'session_token') = True) then
  begin
    if (CkJsonObject_JsonTypeOf(credentials,'session_token') <> 1) then
      begin
        Memo1.Lines.Add('session_token must be a string.');
        Exit;
      end;
    if (CkJsonObject__stringOf(credentials,'session_token') <> '') then
      begin
        success := CkRest_AddQueryParam(rest,'X-Amz-Security-Token',CkJsonObject__stringOf(credentials,'session_token'));
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not set the session-token parameter.');
            Exit;
          end;
      end;
  end;
//  Supply a Socket to explicitly enable TLS certificate verification.
connection := CkSocket_Create();
CkSocket_putRequireSslCertVerify(connection,True);
CkSocket_putMaxReadIdleMs(connection,60000);
CkSocket_putMaxSendIdleMs(connection,60000);
success := CkSocket_Connect(connection,CkStringBuilder__getAsString(endpoint),443,True,20000);
if (success <> True) then
  begin
    Memo1.Lines.Add('TLS connection failed; inspect diagnostics privately.');
    Exit;
  end;
success := CkRest_UseConnection(rest,connection,True);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not attach the TLS connection.');
    Exit;
  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.
xml := CkXml_Create();
CkXml_putStrict(xml,True);
success := CkRest_AddQueryParam(rest,'Version','2016-11-15');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set Version.');
    Exit;
  end;
responseXml := '';
errorCode := '';
volumeId := 'vol-0123456789abcdef0';
dryRun := True;
//  Serialize access. Keep this checkpoint after any uncertain create response.
checkpointFile := 'ec2-snapshot-request.json';
files := CkFileAccess_Create();
checkpoint := CkJsonObject_Create();
CkJsonObject_putStrict(checkpoint,True);
snapshotId := '';
fileStatus := CkFileAccess_FileExists3(files,checkpointFile);
if (fileStatus <> 0) then
  begin
    if (fileStatus <> 1) then
      begin
        Memo1.Lines.Add('Snapshot checkpoint path is inaccessible or is not a file.');
        Exit;
      end;
    success := CkJsonObject_LoadFile(checkpoint,checkpointFile);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not read snapshot checkpoint.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(checkpoint,'region') <> 1) or (CkJsonObject__stringOf(checkpoint,'region') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid saved region.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(checkpoint,'volume_id') <> 1) or (CkJsonObject__stringOf(checkpoint,'volume_id') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid saved volume_id.');
        Exit;
      end;
    if ((CkJsonObject__stringOf(checkpoint,'region') <> region) or (CkJsonObject__stringOf(checkpoint,'volume_id') <> volumeId)) then
      begin
        Memo1.Lines.Add('Checkpoint belongs to another region or volume.');
        Exit;
      end;
    if (CkJsonObject_HasMember(checkpoint,'snapshot_id') <> True) then
      begin
        Memo1.Lines.Add('An earlier create outcome is uncertain. Reconcile it before another CreateSnapshot.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(checkpoint,'snapshot_id') <> 1) or (CkJsonObject__stringOf(checkpoint,'snapshot_id') = '')) then
      begin
        Memo1.Lines.Add('Missing or invalid saved snapshot_id.');
        Exit;
      end;
    snapshotId := CkJsonObject__stringOf(checkpoint,'snapshot_id');
    Memo1.Lines.Add('Resuming read-only status checks for ' + snapshotId);
  end;
if (snapshotId = '') then
  begin
    if (dryRun = False) then
      begin
        started := CkDateTime_Create();
        success := CkDateTime_SetFromCurrentSystemTime(started);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not read the current time.');
            Exit;
          end;
        success := CkJsonObject_UpdateString(checkpoint,'region',region);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not record region.');
            Exit;
          end;
        success := CkJsonObject_UpdateString(checkpoint,'volume_id',volumeId);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not record volume.');
            Exit;
          end;
        success := CkJsonObject_UpdateString(checkpoint,'requested_at',CkDateTime__getAsTimestamp(started,False));
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not record request time.');
            Exit;
          end;
        success := CkJsonObject_WriteFile(checkpoint,checkpointFile);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not persist create intent; no snapshot request sent.');
            Exit;
          end;
      end;
    success := CkRest_AddQueryParam(rest,'Action','CreateSnapshot');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not set Action.');
        Exit;
      end;
    success := CkRest_AddQueryParam(rest,'VolumeId',volumeId);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not set VolumeId.');
        Exit;
      end;
    success := CkRest_AddQueryParam(rest,'Description','Example volume snapshot');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not set Description.');
        Exit;
      end;
    if (dryRun = True) then
      begin
        success := CkRest_AddQueryParam(rest,'DryRun','true');
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not set DryRun.');
            Exit;
          end;
      end;
    responseXml := CkRest__fullRequestNoBody(rest,'GET','/');
    if (CkRest_getLastMethodSuccess(rest) <> True) then
      begin
        Memo1.Lines.Add('Request did not complete; inspect diagnostics privately.');
        //  The operation might already have been accepted. Check state before retrying.
        Exit;
      end;
    success := CkXml_LoadXml(xml,responseXml);
    if (CkRest_getResponseStatusCode(rest) <> 200) then
      begin
        Memo1.Lines.Add('EC2 HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
        if (success = True) then
          begin
            if (CkXml_HasChildWithTag(xml,'Errors|Error|Code') = True) then
              begin
                errorCode := CkXml__getChildContent(xml,'Errors|Error|Code');
                if ((dryRun = True) and (errorCode = 'DryRunOperation')) then
                  begin
                    Memo1.Lines.Add('Dry run authorized. No resource was changed.');
                    Memo1.Lines.Add('Set dryRun to false only when ready to perform the operation.');
                    Exit;
                  end;
                Memo1.Lines.Add('AWS error code: ' + errorCode);
              end;
            if (CkXml_HasChildWithTag(xml,'RequestID') = True) then
              begin
                Memo1.Lines.Add('AWS request ID: ' + CkXml__getChildContent(xml,'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.
        Exit;
      end;
    if (success <> True) then
      begin
        Memo1.Lines.Add('Expected a well-formed XML response.');
        Exit;
      end;
    if (CkXml__tag(xml) <> 'CreateSnapshotResponse') then
      begin
        Memo1.Lines.Add('Unexpected EC2 response element.');
        Exit;
      end;
    if (dryRun = True) then
      begin
        Memo1.Lines.Add('Unexpected HTTP 200 for a dry run; do not treat this as authorization to proceed.');
        Exit;
      end;
    if ((CkXml_HasChildWithTag(xml,'requestId') <> True) or (CkXml__getChildContent(xml,'requestId') = '')) then
      begin
        Memo1.Lines.Add('Missing or empty requestId.');
        Exit;
      end;
    Memo1.Lines.Add('AWS request ID: ' + CkXml__getChildContent(xml,'requestId'));
    if ((CkXml_HasChildWithTag(xml,'snapshotId') <> True) or (CkXml__getChildContent(xml,'snapshotId') = '')) then
      begin
        Memo1.Lines.Add('Missing or empty snapshotId.');
        Exit;
      end;
    snapshotId := CkXml__getChildContent(xml,'snapshotId');
    Memo1.Lines.Add('Snapshot creation accepted: ' + snapshotId);
    success := CkJsonObject_UpdateString(checkpoint,'snapshot_id',snapshotId);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not record snapshot ID; save the displayed ID privately.');
        Exit;
      end;
    success := CkJsonObject_WriteFile(checkpoint,checkpointFile);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Snapshot accepted but checkpoint save failed; record the ID before continuing.');
        Exit;
      end;
    success := CkRest_RemoveQueryParam(rest,'Action');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not change action.');
        Exit;
      end;
    success := CkRest_RemoveQueryParam(rest,'VolumeId');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not remove create parameter.');
        Exit;
      end;
    success := CkRest_RemoveQueryParam(rest,'Description');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not remove description.');
        Exit;
      end;
  end;
//  Keep the signed session token and Version; remove only the prior action's parameters.
success := CkRest_AddQueryParam(rest,'Action','DescribeSnapshots');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set Action.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'SnapshotId.1',snapshotId);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set SnapshotId.1.');
    Exit;
  end;
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.
attempt := 0;
delayMs := 2000;
retryRead := False;
while (attempt < 60) do
  begin
    retryRead := False;
    responseXml := CkRest__fullRequestNoBody(rest,'GET','/');
    if (CkRest_getLastMethodSuccess(rest) <> True) then
      begin
        Memo1.Lines.Add('Polling transport failed; resume the read later. No write was retried.');
        Exit;
      end;
    success := CkXml_LoadXml(xml,responseXml);
    if (CkRest_getResponseStatusCode(rest) <> 200) then
      begin
        errorCode := '';
        if (success = True) then
          begin
            if (CkXml_HasChildWithTag(xml,'Errors|Error|Code') = True) then
              begin
                errorCode := CkXml__getChildContent(xml,'Errors|Error|Code');
              end;
          end;
        if ((errorCode = 'RequestLimitExceeded') or (errorCode = 'InternalError') or (errorCode = 'ServiceUnavailable') or (errorCode = 'InvalidSnapshot.NotFound')) then
          begin
            retryRead := True;
          end
        else
          begin
            Memo1.Lines.Add('Polling failed: HTTP ' + IntToStr(CkRest_getResponseStatusCode(rest)) + '; AWS code: ' + errorCode);
            Exit;
          end;
      end;
    if (retryRead = False) then
      begin
        if (success <> True) then
          begin
            Memo1.Lines.Add('Expected a well-formed XML response.');
            Exit;
          end;
        if (CkXml__tag(xml) <> 'DescribeSnapshotsResponse') then
          begin
            Memo1.Lines.Add('Unexpected polling response.');
            Exit;
          end;
        if ((CkXml_HasChildWithTag(xml,'requestId') <> True) or (CkXml__getChildContent(xml,'requestId') = '')) then
          begin
            Memo1.Lines.Add('Missing or empty requestId.');
            Exit;
          end;
        if (CkXml_HasChildWithTag(xml,'snapshotSet') <> True) then
          begin
            Memo1.Lines.Add('Expected snapshotSet.');
            Exit;
          end;
        if (CkXml_NumChildrenAt(xml,'snapshotSet') > 0) then
          begin
            if (CkXml_NumChildrenAt(xml,'snapshotSet') <> 1) then
              begin
                Memo1.Lines.Add('Expected one snapshot.');
                Exit;
              end;
            if ((CkXml_HasChildWithTag(xml,'snapshotSet|item|snapshotId') <> True) or (CkXml__getChildContent(xml,'snapshotSet|item|snapshotId') = '')) then
              begin
                Memo1.Lines.Add('Missing or empty snapshotSet|item|snapshotId.');
                Exit;
              end;
            if (CkXml__getChildContent(xml,'snapshotSet|item|snapshotId') <> snapshotId) then
              begin
                Memo1.Lines.Add('Unexpected snapshot ID.');
                Exit;
              end;
            if ((CkXml_HasChildWithTag(xml,'snapshotSet|item|status') <> True) or (CkXml__getChildContent(xml,'snapshotSet|item|status') = '')) then
              begin
                Memo1.Lines.Add('Missing or empty snapshotSet|item|status.');
                Exit;
              end;
            state := CkXml__getChildContent(xml,'snapshotSet|item|status');
            Memo1.Lines.Add('Snapshot state: ' + state);
            if (CkXml_HasChildWithTag(xml,'snapshotSet|item|progress') = True) then
              begin
                Memo1.Lines.Add('Progress: ' + CkXml__getChildContent(xml,'snapshotSet|item|progress'));
              end;
            if (state = 'completed') then
              begin
                Memo1.Lines.Add('Snapshot completed: ' + snapshotId);
                Exit;
              end;
            if (state = 'error') then
              begin
                Memo1.Lines.Add('Snapshot entered error state. Inspect details privately; do not create another automatically.');
                Exit;
              end;
          end;
      end;
    attempt := attempt + 1;
    if (attempt < 60) then
      begin
        CkSocket_SleepMs(connection,delayMs);
        if (delayMs < 10000) then
          begin
            delayMs := delayMs * 2;
            if (delayMs > 10000) then
              begin
                delayMs := 10000;
              end;
          end;
      end;
  end;

Memo1.Lines.Add('Polling limit reached; completion has not been confirmed. Resume checking later.');

CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkFileAccess_Dispose(files);
CkJsonObject_Dispose(checkpoint);
        CkDateTime_Dispose(started);