Amazon EC2: Launch an Instance with a Persisted Idempotency Token
See more Amazon EC2 Examples
Live mode creates a billable instance. Before the first run, select an AMI compatible with the instance type, a subnet, a security group in that subnet's VPC, and an existing key pair, all in the chosen region. The sample requires IMDSv2. Public addressing follows the subnet configuration; this is not a promise of Internet reachability.
The private ec2-launch-request.json stores the region, exact illustrated parameters, and client token before submission, and the resulting instance ID after success. Reruns load the saved parameters; changing constants in the source does not change an existing request. Serialize access to this file and retain it after timeouts. Deliberate retries must use the same token and unchanged parameters in the same region/subnet; a different Availability Zone can create another instance. Reconcile uncertain outcomes by client token before creating a new intent. A recorded instance ID prevents this sample from resubmitting. Launch is asynchronous; use Wait for Instance State and Health Checks.
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:RunInstances. 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.
Chilkat Objective-C Downloads
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoStringBuilder.h>
#import <CkoAuthAws.h>
#import <CkoRest.h>
#import <CkoSocket.h>
#import <CkoXml.h>
#import <CkoFileAccess.h>
#import <CkoCrypt2.h>
// Assumes Chilkat is unlocked. See Global Unlock Sample.
BOOL success = NO;
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the EC2 operation.
CkoJsonObject *credentials = [[CkoJsonObject alloc] init];
credentials.Strict = YES;
success = [credentials LoadFile: @"qa_data/aws/ec2.json"];
if (success != YES) {
NSLog(@"%@",@"Could not load private AWS credentials.");
return;
}
if (([[credentials JsonTypeOf: @"access_key"] intValue] != 1) || ([credentials StringOf: @"access_key"] == @"")) {
NSLog(@"%@",@"Missing or invalid access_key.");
return;
}
if (([[credentials JsonTypeOf: @"secret_key"] intValue] != 1) || ([credentials StringOf: @"secret_key"] == @"")) {
NSLog(@"%@",@"Missing or invalid secret_key.");
return;
}
// Set this once to the region containing the instances.
NSString *region = @"us-west-2";
CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
[endpoint Append: @"ec2."];
[endpoint Append: region];
[endpoint Append: @".amazonaws.com"];
CkoAuthAws *aws = [[CkoAuthAws alloc] init];
aws.AccessKey = [credentials StringOf: @"access_key"];
aws.SecretKey = [credentials StringOf: @"secret_key"];
aws.Region = region;
aws.ServiceName = @"ec2";
aws.SignatureVersion = [NSNumber numberWithInt:4];
CkoRest *rest = [[CkoRest alloc] init];
rest.ConnectTimeoutMs = [NSNumber numberWithInt:20000];
rest.IdleTimeoutMs = [NSNumber numberWithInt:60000];
success = [rest SetAuthAws: aws];
if (success != YES) {
NSLog(@"%@",@"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"] == YES) {
if ([[credentials JsonTypeOf: @"session_token"] intValue] != 1) {
NSLog(@"%@",@"session_token must be a string.");
return;
}
if ([credentials StringOf: @"session_token"] != @"") {
success = [rest AddQueryParam: @"X-Amz-Security-Token" value: [credentials StringOf: @"session_token"]];
if (success != YES) {
NSLog(@"%@",@"Could not set the session-token parameter.");
return;
}
}
}
// Supply a Socket to explicitly enable TLS certificate verification.
CkoSocket *connection = [[CkoSocket alloc] init];
connection.RequireSslCertVerify = YES;
connection.MaxReadIdleMs = [NSNumber numberWithInt:60000];
connection.MaxSendIdleMs = [NSNumber numberWithInt:60000];
success = [connection Connect: [endpoint GetAsString] port: [NSNumber numberWithInt: 443] ssl: YES maxWaitMs: [NSNumber numberWithInt: 20000]];
if (success != YES) {
NSLog(@"%@",@"TLS connection failed; inspect diagnostics privately.");
return;
}
success = [rest UseConnection: connection autoReconnect: YES];
if (success != YES) {
NSLog(@"%@",@"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.
CkoXml *xml = [[CkoXml alloc] init];
xml.Strict = YES;
success = [rest AddQueryParam: @"Version" value: @"2016-11-15"];
if (success != YES) {
NSLog(@"%@",@"Could not set Version.");
return;
}
NSString *responseXml = @"";
NSString *errorCode = @"";
BOOL dryRun = YES;
// Serialize access to this private file. Use a new file only for a NEW intended launch.
NSString *launchFile = @"ec2-launch-request.json";
CkoFileAccess *files = [[CkoFileAccess alloc] init];
CkoJsonObject *launch = [[CkoJsonObject alloc] init];
launch.Strict = YES;
int fileStatus = [[files FileExists3: launchFile] intValue];
if (fileStatus == 0) {
// Replace these sample settings before the first run. Later runs use the saved file.
CkoCrypt2 *uuid = [[CkoCrypt2 alloc] init];
NSString *clientToken = [uuid GenerateUuid];
CkoStringBuilder *tokenText = [[CkoStringBuilder alloc] init];
[tokenText Append: clientToken];
if ([tokenText.Length intValue] != 36) {
NSLog(@"%@",@"Could not generate a launch token.");
return;
}
success = [launch UpdateString: @"client_token" value: clientToken];
if (success != YES) {
NSLog(@"%@",@"Could not save client token.");
return;
}
success = [launch UpdateString: @"region" value: region];
if (success != YES) {
NSLog(@"%@",@"Could not save region.");
return;
}
success = [launch UpdateString: @"image_id" value: @"ami-0123456789abcdef0"];
if (success != YES) {
NSLog(@"%@",@"Could not prepare image_id.");
return;
}
success = [launch UpdateString: @"instance_type" value: @"t3.micro"];
if (success != YES) {
NSLog(@"%@",@"Could not prepare instance_type.");
return;
}
success = [launch UpdateString: @"subnet_id" value: @"subnet-0123456789abcdef0"];
if (success != YES) {
NSLog(@"%@",@"Could not prepare subnet_id.");
return;
}
success = [launch UpdateString: @"security_group_id" value: @"sg-0123456789abcdef0"];
if (success != YES) {
NSLog(@"%@",@"Could not prepare security_group_id.");
return;
}
success = [launch UpdateString: @"key_name" value: @"my-key-pair"];
if (success != YES) {
NSLog(@"%@",@"Could not prepare key_name.");
return;
}
success = [launch UpdateString: @"min_count" value: @"1"];
if (success != YES) {
NSLog(@"%@",@"Could not prepare min_count.");
return;
}
success = [launch UpdateString: @"max_count" value: @"1"];
if (success != YES) {
NSLog(@"%@",@"Could not prepare max_count.");
return;
}
success = [launch UpdateString: @"http_tokens" value: @"required"];
if (success != YES) {
NSLog(@"%@",@"Could not prepare http_tokens.");
return;
}
success = [launch UpdateString: @"http_endpoint" value: @"enabled"];
if (success != YES) {
NSLog(@"%@",@"Could not prepare http_endpoint.");
return;
}
}
else {
if (fileStatus != 1) {
NSLog(@"%@",@"Launch path is inaccessible or is not a regular file.");
return;
}
success = [launch LoadFile: launchFile];
if (success != YES) {
NSLog(@"%@",@"Could not load the saved launch request.");
return;
}
}
if (([[launch JsonTypeOf: @"region"] intValue] != 1) || ([launch StringOf: @"region"] == @"")) {
NSLog(@"%@",@"Missing or invalid saved region.");
return;
}
if (([[launch JsonTypeOf: @"client_token"] intValue] != 1) || ([launch StringOf: @"client_token"] == @"")) {
NSLog(@"%@",@"Missing or invalid saved client_token.");
return;
}
if (([[launch JsonTypeOf: @"image_id"] intValue] != 1) || ([launch StringOf: @"image_id"] == @"")) {
NSLog(@"%@",@"Missing or invalid saved image_id.");
return;
}
if (([[launch JsonTypeOf: @"instance_type"] intValue] != 1) || ([launch StringOf: @"instance_type"] == @"")) {
NSLog(@"%@",@"Missing or invalid saved instance_type.");
return;
}
if (([[launch JsonTypeOf: @"subnet_id"] intValue] != 1) || ([launch StringOf: @"subnet_id"] == @"")) {
NSLog(@"%@",@"Missing or invalid saved subnet_id.");
return;
}
if (([[launch JsonTypeOf: @"security_group_id"] intValue] != 1) || ([launch StringOf: @"security_group_id"] == @"")) {
NSLog(@"%@",@"Missing or invalid saved security_group_id.");
return;
}
if (([[launch JsonTypeOf: @"key_name"] intValue] != 1) || ([launch StringOf: @"key_name"] == @"")) {
NSLog(@"%@",@"Missing or invalid saved key_name.");
return;
}
if (([[launch JsonTypeOf: @"min_count"] intValue] != 1) || ([launch StringOf: @"min_count"] == @"")) {
NSLog(@"%@",@"Missing or invalid saved min_count.");
return;
}
if (([[launch JsonTypeOf: @"max_count"] intValue] != 1) || ([launch StringOf: @"max_count"] == @"")) {
NSLog(@"%@",@"Missing or invalid saved max_count.");
return;
}
if (([[launch JsonTypeOf: @"http_tokens"] intValue] != 1) || ([launch StringOf: @"http_tokens"] == @"")) {
NSLog(@"%@",@"Missing or invalid saved http_tokens.");
return;
}
if (([[launch JsonTypeOf: @"http_endpoint"] intValue] != 1) || ([launch StringOf: @"http_endpoint"] == @"")) {
NSLog(@"%@",@"Missing or invalid saved http_endpoint.");
return;
}
if ([launch StringOf: @"region"] != region) {
NSLog(@"%@",@"Saved launch region differs; do not reuse this token in another region.");
return;
}
if (([launch StringOf: @"min_count"] != @"1") || ([launch StringOf: @"max_count"] != @"1")) {
NSLog(@"%@",@"This demonstration launches exactly one instance.");
return;
}
if ([launch HasMember: @"instance_id"] == YES) {
if (([[launch JsonTypeOf: @"instance_id"] intValue] != 1) || ([launch StringOf: @"instance_id"] == @"")) {
NSLog(@"%@",@"Missing or invalid saved instance_id.");
return;
}
NSLog(@"%@%@",@"Launch already recorded for instance: ",[launch StringOf: @"instance_id"]);
NSLog(@"%@",@"No new launch request was sent.");
return;
}
// Persist before sending, including dry runs. Never generate a new token for a retry.
success = [launch WriteFile: launchFile];
if (success != YES) {
NSLog(@"%@",@"Could not persist launch parameters; no launch sent.");
return;
}
success = [rest AddQueryParam: @"Action" value: @"RunInstances"];
if (success != YES) {
NSLog(@"%@",@"Could not set Action.");
return;
}
success = [rest AddQueryParam: @"ClientToken" value: [launch StringOf: @"client_token"]];
if (success != YES) {
NSLog(@"%@",@"Could not set ClientToken.");
return;
}
success = [rest AddQueryParam: @"ImageId" value: [launch StringOf: @"image_id"]];
if (success != YES) {
NSLog(@"%@",@"Could not set ImageId.");
return;
}
success = [rest AddQueryParam: @"InstanceType" value: [launch StringOf: @"instance_type"]];
if (success != YES) {
NSLog(@"%@",@"Could not set InstanceType.");
return;
}
success = [rest AddQueryParam: @"SubnetId" value: [launch StringOf: @"subnet_id"]];
if (success != YES) {
NSLog(@"%@",@"Could not set SubnetId.");
return;
}
success = [rest AddQueryParam: @"SecurityGroupId.1" value: [launch StringOf: @"security_group_id"]];
if (success != YES) {
NSLog(@"%@",@"Could not set SecurityGroupId.1.");
return;
}
success = [rest AddQueryParam: @"KeyName" value: [launch StringOf: @"key_name"]];
if (success != YES) {
NSLog(@"%@",@"Could not set KeyName.");
return;
}
success = [rest AddQueryParam: @"MinCount" value: [launch StringOf: @"min_count"]];
if (success != YES) {
NSLog(@"%@",@"Could not set MinCount.");
return;
}
success = [rest AddQueryParam: @"MaxCount" value: [launch StringOf: @"max_count"]];
if (success != YES) {
NSLog(@"%@",@"Could not set MaxCount.");
return;
}
success = [rest AddQueryParam: @"MetadataOptions.HttpTokens" value: [launch StringOf: @"http_tokens"]];
if (success != YES) {
NSLog(@"%@",@"Could not set MetadataOptions.HttpTokens.");
return;
}
success = [rest AddQueryParam: @"MetadataOptions.HttpEndpoint" value: [launch StringOf: @"http_endpoint"]];
if (success != YES) {
NSLog(@"%@",@"Could not set MetadataOptions.HttpEndpoint.");
return;
}
if (dryRun == YES) {
success = [rest AddQueryParam: @"DryRun" value: @"true"];
if (success != YES) {
NSLog(@"%@",@"Could not set DryRun.");
return;
}
}
responseXml = [rest FullRequestNoBody: @"GET" uriPath: @"/"];
if (rest.LastMethodSuccess != YES) {
NSLog(@"%@",@"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 intValue] != 200) {
NSLog(@"%@%d",@"EC2 HTTP status: ",[rest.ResponseStatusCode intValue]);
if (success == YES) {
if ([xml HasChildWithTag: @"Errors|Error|Code"] == YES) {
errorCode = [xml GetChildContent: @"Errors|Error|Code"];
if ((dryRun == YES) && (errorCode == @"DryRunOperation")) {
NSLog(@"%@",@"Dry run authorized. No resource was changed.");
NSLog(@"%@",@"Set dryRun to false only when ready to perform the operation.");
return;
}
NSLog(@"%@%@",@"AWS error code: ",errorCode);
}
if ([xml HasChildWithTag: @"RequestID"] == YES) {
NSLog(@"%@%@",@"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 != YES) {
NSLog(@"%@",@"Expected a well-formed XML response.");
return;
}
if (xml.Tag != @"RunInstancesResponse") {
NSLog(@"%@",@"Unexpected EC2 response element.");
return;
}
if (dryRun == YES) {
NSLog(@"%@",@"Unexpected HTTP 200 for a dry run; do not treat this as authorization to proceed.");
return;
}
if (([xml HasChildWithTag: @"requestId"] != YES) || ([xml GetChildContent: @"requestId"] == @"")) {
NSLog(@"%@",@"Missing or empty requestId.");
return;
}
NSLog(@"%@%@",@"AWS request ID: ",[xml GetChildContent: @"requestId"]);
if ([[xml NumChildrenAt: @"instancesSet"] intValue] != 1) {
NSLog(@"%@",@"Expected exactly one launched instance; reconcile using the saved client token.");
return;
}
if (([xml HasChildWithTag: @"instancesSet|item|instanceId"] != YES) || ([xml GetChildContent: @"instancesSet|item|instanceId"] == @"")) {
NSLog(@"%@",@"Missing or empty instancesSet|item|instanceId.");
return;
}
NSString *instanceId = [xml GetChildContent: @"instancesSet|item|instanceId"];
NSLog(@"%@%@",@"Launch accepted for instance: ",instanceId);
if ([xml HasChildWithTag: @"instancesSet|item|instanceState|name"] == YES) {
NSLog(@"%@%@",@"State: ",[xml GetChildContent: @"instancesSet|item|instanceState|name"]);
}
success = [launch UpdateString: @"instance_id" value: instanceId];
if (success != YES) {
NSLog(@"%@",@"Could not record the returned instance ID; keep it privately.");
return;
}
success = [launch WriteFile: launchFile];
if (success != YES) {
NSLog(@"%@",@"Launch accepted but the result could not be saved. Record the ID before retrying.");
return;
}
NSLog(@"%@",@"Saved instance ID. Wait for running state and health before use.");