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