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 Xojo Plugin Downloads
// Assumes Chilkat is unlocked. See Global Unlock Sample.
Dim success As Boolean
success = False
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the EC2 operation.
Dim credentials As New Chilkat.JsonObject
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/ec2.json")
If (success <> True) Then
System.DebugLog("Could not load private AWS credentials.")
Return
End If
If ((credentials.JsonTypeOf("access_key") <> 1) Or (credentials.StringOf("access_key") = "")) Then
System.DebugLog("Missing or invalid access_key.")
Return
End If
If ((credentials.JsonTypeOf("secret_key") <> 1) Or (credentials.StringOf("secret_key") = "")) Then
System.DebugLog("Missing or invalid secret_key.")
Return
End If
// Set this once to the region containing the instances.
Dim region As String
region = "us-west-2"
Dim endpoint As New Chilkat.StringBuilder
success = endpoint.Append("ec2.")
success = endpoint.Append(region)
success = endpoint.Append(".amazonaws.com")
Dim aws As New Chilkat.AuthAws
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "ec2"
aws.SignatureVersion = 4
Dim rest As New Chilkat.Rest
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
success = rest.SetAuthAws(aws)
If (success <> True) Then
System.DebugLog("Could not configure AWS signing.")
Return
End If
// 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.HasMember("session_token") = True) Then
If (credentials.JsonTypeOf("session_token") <> 1) Then
System.DebugLog("session_token must be a string.")
Return
End If
If (credentials.StringOf("session_token") <> "") Then
success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"))
If (success <> True) Then
System.DebugLog("Could not set the session-token parameter.")
Return
End If
End If
End If
// Supply a Socket to explicitly enable TLS certificate verification.
Dim connection As New Chilkat.Socket
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,True,20000)
If (success <> True) Then
System.DebugLog("TLS connection failed; inspect diagnostics privately.")
Return
End If
success = rest.UseConnection(connection,True)
If (success <> True) Then
System.DebugLog("Could not attach the TLS connection.")
Return
End If
// 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.
Dim xml As New Chilkat.Xml
xml.Strict = True
success = rest.AddQueryParam("Version","2016-11-15")
If (success <> True) Then
System.DebugLog("Could not set Version.")
Return
End If
Dim responseXml As String
responseXml = ""
Dim errorCode As String
errorCode = ""
Dim volumeId As String
volumeId = "vol-0123456789abcdef0"
Dim dryRun As Boolean
dryRun = True
// Serialize access. Keep this checkpoint after any uncertain create response.
Dim checkpointFile As String
checkpointFile = "ec2-snapshot-request.json"
Dim files As New Chilkat.FileAccess
Dim checkpoint As New Chilkat.JsonObject
checkpoint.Strict = True
Dim snapshotId As String
snapshotId = ""
Dim fileStatus As Int32
fileStatus = files.FileExists3(checkpointFile)
If (fileStatus <> 0) Then
If (fileStatus <> 1) Then
System.DebugLog("Snapshot checkpoint path is inaccessible or is not a file.")
Return
End If
success = checkpoint.LoadFile(checkpointFile)
If (success <> True) Then
System.DebugLog("Could not read snapshot checkpoint.")
Return
End If
If ((checkpoint.JsonTypeOf("region") <> 1) Or (checkpoint.StringOf("region") = "")) Then
System.DebugLog("Missing or invalid saved region.")
Return
End If
If ((checkpoint.JsonTypeOf("volume_id") <> 1) Or (checkpoint.StringOf("volume_id") = "")) Then
System.DebugLog("Missing or invalid saved volume_id.")
Return
End If
If ((checkpoint.StringOf("region") <> region) Or (checkpoint.StringOf("volume_id") <> volumeId)) Then
System.DebugLog("Checkpoint belongs to another region or volume.")
Return
End If
If (checkpoint.HasMember("snapshot_id") <> True) Then
System.DebugLog("An earlier create outcome is uncertain. Reconcile it before another CreateSnapshot.")
Return
End If
If ((checkpoint.JsonTypeOf("snapshot_id") <> 1) Or (checkpoint.StringOf("snapshot_id") = "")) Then
System.DebugLog("Missing or invalid saved snapshot_id.")
Return
End If
snapshotId = checkpoint.StringOf("snapshot_id")
System.DebugLog("Resuming read-only status checks for " + snapshotId)
End If
If (snapshotId = "") Then
If (dryRun = False) Then
Dim started As New Chilkat.CkDateTime
success = started.SetFromCurrentSystemTime()
If (success <> True) Then
System.DebugLog("Could not read the current time.")
Return
End If
success = checkpoint.UpdateString("region",region)
If (success <> True) Then
System.DebugLog("Could not record region.")
Return
End If
success = checkpoint.UpdateString("volume_id",volumeId)
If (success <> True) Then
System.DebugLog("Could not record volume.")
Return
End If
success = checkpoint.UpdateString("requested_at",started.GetAsTimestamp(False))
If (success <> True) Then
System.DebugLog("Could not record request time.")
Return
End If
success = checkpoint.WriteFile(checkpointFile)
If (success <> True) Then
System.DebugLog("Could not persist create intent; no snapshot request sent.")
Return
End If
End If
success = rest.AddQueryParam("Action","CreateSnapshot")
If (success <> True) Then
System.DebugLog("Could not set Action.")
Return
End If
success = rest.AddQueryParam("VolumeId",volumeId)
If (success <> True) Then
System.DebugLog("Could not set VolumeId.")
Return
End If
success = rest.AddQueryParam("Description","Example volume snapshot")
If (success <> True) Then
System.DebugLog("Could not set Description.")
Return
End If
If (dryRun = True) Then
success = rest.AddQueryParam("DryRun","true")
If (success <> True) Then
System.DebugLog("Could not set DryRun.")
Return
End If
End If
responseXml = rest.FullRequestNoBody("GET","/")
If (rest.LastMethodSuccess <> True) Then
System.DebugLog("Request did not complete; inspect diagnostics privately.")
// The operation might already have been accepted. Check state before retrying.
Return
End If
success = xml.LoadXml(responseXml)
If (rest.ResponseStatusCode <> 200) Then
System.DebugLog("EC2 HTTP status: " + Str(rest.ResponseStatusCode))
If (success = True) Then
If (xml.HasChildWithTag("Errors|Error|Code") = True) Then
errorCode = xml.GetChildContent("Errors|Error|Code")
If ((dryRun = True) And (errorCode = "DryRunOperation")) Then
System.DebugLog("Dry run authorized. No resource was changed.")
System.DebugLog("Set dryRun to false only when ready to perform the operation.")
Return
End If
System.DebugLog("AWS error code: " + errorCode)
End If
If (xml.HasChildWithTag("RequestID") = True) Then
System.DebugLog("AWS request ID: " + xml.GetChildContent("RequestID"))
End If
End If
// 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
If (success <> True) Then
System.DebugLog("Expected a well-formed XML response.")
Return
End If
If (xml.Tag <> "CreateSnapshotResponse") Then
System.DebugLog("Unexpected EC2 response element.")
Return
End If
If (dryRun = True) Then
System.DebugLog("Unexpected HTTP 200 for a dry run; do not treat this as authorization to proceed.")
Return
End If
If ((xml.HasChildWithTag("requestId") <> True) Or (xml.GetChildContent("requestId") = "")) Then
System.DebugLog("Missing or empty requestId.")
Return
End If
System.DebugLog("AWS request ID: " + xml.GetChildContent("requestId"))
If ((xml.HasChildWithTag("snapshotId") <> True) Or (xml.GetChildContent("snapshotId") = "")) Then
System.DebugLog("Missing or empty snapshotId.")
Return
End If
snapshotId = xml.GetChildContent("snapshotId")
System.DebugLog("Snapshot creation accepted: " + snapshotId)
success = checkpoint.UpdateString("snapshot_id",snapshotId)
If (success <> True) Then
System.DebugLog("Could not record snapshot ID; save the displayed ID privately.")
Return
End If
success = checkpoint.WriteFile(checkpointFile)
If (success <> True) Then
System.DebugLog("Snapshot accepted but checkpoint save failed; record the ID before continuing.")
Return
End If
success = rest.RemoveQueryParam("Action")
If (success <> True) Then
System.DebugLog("Could not change action.")
Return
End If
success = rest.RemoveQueryParam("VolumeId")
If (success <> True) Then
System.DebugLog("Could not remove create parameter.")
Return
End If
success = rest.RemoveQueryParam("Description")
If (success <> True) Then
System.DebugLog("Could not remove description.")
Return
End If
End If
// Keep the signed session token and Version; remove only the prior action's parameters.
success = rest.AddQueryParam("Action","DescribeSnapshots")
If (success <> True) Then
System.DebugLog("Could not set Action.")
Return
End If
success = rest.AddQueryParam("SnapshotId.1",snapshotId)
If (success <> True) Then
System.DebugLog("Could not set SnapshotId.1.")
Return
End If
Dim state As String
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.
Dim attempt As Int32
attempt = 0
Dim delayMs As Int32
delayMs = 2000
Dim retryRead As Boolean
retryRead = False
While (attempt < 60)
retryRead = False
responseXml = rest.FullRequestNoBody("GET","/")
If (rest.LastMethodSuccess <> True) Then
System.DebugLog("Polling transport failed; resume the read later. No write was retried.")
Return
End If
success = xml.LoadXml(responseXml)
If (rest.ResponseStatusCode <> 200) Then
errorCode = ""
If (success = True) Then
If (xml.HasChildWithTag("Errors|Error|Code") = True) Then
errorCode = xml.GetChildContent("Errors|Error|Code")
End If
End If
If ((errorCode = "RequestLimitExceeded") Or (errorCode = "InternalError") Or (errorCode = "ServiceUnavailable") Or (errorCode = "InvalidSnapshot.NotFound")) Then
retryRead = True
Else
System.DebugLog("Polling failed: HTTP " + Str(rest.ResponseStatusCode) + "; AWS code: " + errorCode)
Return
End If
End If
If (retryRead = False) Then
If (success <> True) Then
System.DebugLog("Expected a well-formed XML response.")
Return
End If
If (xml.Tag <> "DescribeSnapshotsResponse") Then
System.DebugLog("Unexpected polling response.")
Return
End If
If ((xml.HasChildWithTag("requestId") <> True) Or (xml.GetChildContent("requestId") = "")) Then
System.DebugLog("Missing or empty requestId.")
Return
End If
If (xml.HasChildWithTag("snapshotSet") <> True) Then
System.DebugLog("Expected snapshotSet.")
Return
End If
If (xml.NumChildrenAt("snapshotSet") > 0) Then
If (xml.NumChildrenAt("snapshotSet") <> 1) Then
System.DebugLog("Expected one snapshot.")
Return
End If
If ((xml.HasChildWithTag("snapshotSet|item|snapshotId") <> True) Or (xml.GetChildContent("snapshotSet|item|snapshotId") = "")) Then
System.DebugLog("Missing or empty snapshotSet|item|snapshotId.")
Return
End If
If (xml.GetChildContent("snapshotSet|item|snapshotId") <> snapshotId) Then
System.DebugLog("Unexpected snapshot ID.")
Return
End If
If ((xml.HasChildWithTag("snapshotSet|item|status") <> True) Or (xml.GetChildContent("snapshotSet|item|status") = "")) Then
System.DebugLog("Missing or empty snapshotSet|item|status.")
Return
End If
state = xml.GetChildContent("snapshotSet|item|status")
System.DebugLog("Snapshot state: " + state)
If (xml.HasChildWithTag("snapshotSet|item|progress") = True) Then
System.DebugLog("Progress: " + xml.GetChildContent("snapshotSet|item|progress"))
End If
If (state = "completed") Then
System.DebugLog("Snapshot completed: " + snapshotId)
Return
End If
If (state = "error") Then
System.DebugLog("Snapshot entered error state. Inspect details privately; do not create another automatically.")
Return
End If
End If
End If
attempt = attempt + 1
If (attempt < 60) Then
connection.SleepMs delayMs
If (delayMs < 10000) Then
delayMs = delayMs * 2
If (delayMs > 10000) Then
delayMs = 10000
End If
End If
End If
Wend
System.DebugLog("Polling limit reached; completion has not been confirmed. Resume checking later.")