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 Delphi DLL Downloads
var
success: Boolean;
credentials: HCkJsonObject;
region: PWideChar;
endpoint: HCkStringBuilder;
aws: HCkAuthAws;
rest: HCkRest;
connection: HCkSocket;
xml: HCkXml;
responseXml: PWideChar;
errorCode: PWideChar;
dryRun: Boolean;
launchFile: PWideChar;
files: HCkFileAccess;
launch: HCkJsonObject;
fileStatus: Integer;
uuid: HCkCrypt2;
clientToken: PWideChar;
tokenText: HCkStringBuilder;
instanceId: PWideChar;
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 := '';
dryRun := True;
// Serialize access to this private file. Use a new file only for a NEW intended launch.
launchFile := 'ec2-launch-request.json';
files := CkFileAccess_Create();
launch := CkJsonObject_Create();
CkJsonObject_putStrict(launch,True);
fileStatus := CkFileAccess_FileExists3(files,launchFile);
if (fileStatus = 0) then
begin
// Replace these sample settings before the first run. Later runs use the saved file.
uuid := CkCrypt2_Create();
clientToken := CkCrypt2__generateUuid(uuid);
tokenText := CkStringBuilder_Create();
CkStringBuilder_Append(tokenText,clientToken);
if (CkStringBuilder_getLength(tokenText) <> 36) then
begin
Memo1.Lines.Add('Could not generate a launch token.');
Exit;
end;
success := CkJsonObject_UpdateString(launch,'client_token',clientToken);
if (success <> True) then
begin
Memo1.Lines.Add('Could not save client token.');
Exit;
end;
success := CkJsonObject_UpdateString(launch,'region',region);
if (success <> True) then
begin
Memo1.Lines.Add('Could not save region.');
Exit;
end;
success := CkJsonObject_UpdateString(launch,'image_id','ami-0123456789abcdef0');
if (success <> True) then
begin
Memo1.Lines.Add('Could not prepare image_id.');
Exit;
end;
success := CkJsonObject_UpdateString(launch,'instance_type','t3.micro');
if (success <> True) then
begin
Memo1.Lines.Add('Could not prepare instance_type.');
Exit;
end;
success := CkJsonObject_UpdateString(launch,'subnet_id','subnet-0123456789abcdef0');
if (success <> True) then
begin
Memo1.Lines.Add('Could not prepare subnet_id.');
Exit;
end;
success := CkJsonObject_UpdateString(launch,'security_group_id','sg-0123456789abcdef0');
if (success <> True) then
begin
Memo1.Lines.Add('Could not prepare security_group_id.');
Exit;
end;
success := CkJsonObject_UpdateString(launch,'key_name','my-key-pair');
if (success <> True) then
begin
Memo1.Lines.Add('Could not prepare key_name.');
Exit;
end;
success := CkJsonObject_UpdateString(launch,'min_count','1');
if (success <> True) then
begin
Memo1.Lines.Add('Could not prepare min_count.');
Exit;
end;
success := CkJsonObject_UpdateString(launch,'max_count','1');
if (success <> True) then
begin
Memo1.Lines.Add('Could not prepare max_count.');
Exit;
end;
success := CkJsonObject_UpdateString(launch,'http_tokens','required');
if (success <> True) then
begin
Memo1.Lines.Add('Could not prepare http_tokens.');
Exit;
end;
success := CkJsonObject_UpdateString(launch,'http_endpoint','enabled');
if (success <> True) then
begin
Memo1.Lines.Add('Could not prepare http_endpoint.');
Exit;
end;
end
else
begin
if (fileStatus <> 1) then
begin
Memo1.Lines.Add('Launch path is inaccessible or is not a regular file.');
Exit;
end;
success := CkJsonObject_LoadFile(launch,launchFile);
if (success <> True) then
begin
Memo1.Lines.Add('Could not load the saved launch request.');
Exit;
end;
end;
if ((CkJsonObject_JsonTypeOf(launch,'region') <> 1) or (CkJsonObject__stringOf(launch,'region') = '')) then
begin
Memo1.Lines.Add('Missing or invalid saved region.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(launch,'client_token') <> 1) or (CkJsonObject__stringOf(launch,'client_token') = '')) then
begin
Memo1.Lines.Add('Missing or invalid saved client_token.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(launch,'image_id') <> 1) or (CkJsonObject__stringOf(launch,'image_id') = '')) then
begin
Memo1.Lines.Add('Missing or invalid saved image_id.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(launch,'instance_type') <> 1) or (CkJsonObject__stringOf(launch,'instance_type') = '')) then
begin
Memo1.Lines.Add('Missing or invalid saved instance_type.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(launch,'subnet_id') <> 1) or (CkJsonObject__stringOf(launch,'subnet_id') = '')) then
begin
Memo1.Lines.Add('Missing or invalid saved subnet_id.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(launch,'security_group_id') <> 1) or (CkJsonObject__stringOf(launch,'security_group_id') = '')) then
begin
Memo1.Lines.Add('Missing or invalid saved security_group_id.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(launch,'key_name') <> 1) or (CkJsonObject__stringOf(launch,'key_name') = '')) then
begin
Memo1.Lines.Add('Missing or invalid saved key_name.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(launch,'min_count') <> 1) or (CkJsonObject__stringOf(launch,'min_count') = '')) then
begin
Memo1.Lines.Add('Missing or invalid saved min_count.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(launch,'max_count') <> 1) or (CkJsonObject__stringOf(launch,'max_count') = '')) then
begin
Memo1.Lines.Add('Missing or invalid saved max_count.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(launch,'http_tokens') <> 1) or (CkJsonObject__stringOf(launch,'http_tokens') = '')) then
begin
Memo1.Lines.Add('Missing or invalid saved http_tokens.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(launch,'http_endpoint') <> 1) or (CkJsonObject__stringOf(launch,'http_endpoint') = '')) then
begin
Memo1.Lines.Add('Missing or invalid saved http_endpoint.');
Exit;
end;
if (CkJsonObject__stringOf(launch,'region') <> region) then
begin
Memo1.Lines.Add('Saved launch region differs; do not reuse this token in another region.');
Exit;
end;
if ((CkJsonObject__stringOf(launch,'min_count') <> '1') or (CkJsonObject__stringOf(launch,'max_count') <> '1')) then
begin
Memo1.Lines.Add('This demonstration launches exactly one instance.');
Exit;
end;
if (CkJsonObject_HasMember(launch,'instance_id') = True) then
begin
if ((CkJsonObject_JsonTypeOf(launch,'instance_id') <> 1) or (CkJsonObject__stringOf(launch,'instance_id') = '')) then
begin
Memo1.Lines.Add('Missing or invalid saved instance_id.');
Exit;
end;
Memo1.Lines.Add('Launch already recorded for instance: ' + CkJsonObject__stringOf(launch,'instance_id'));
Memo1.Lines.Add('No new launch request was sent.');
Exit;
end;
// Persist before sending, including dry runs. Never generate a new token for a retry.
success := CkJsonObject_WriteFile(launch,launchFile);
if (success <> True) then
begin
Memo1.Lines.Add('Could not persist launch parameters; no launch sent.');
Exit;
end;
success := CkRest_AddQueryParam(rest,'Action','RunInstances');
if (success <> True) then
begin
Memo1.Lines.Add('Could not set Action.');
Exit;
end;
success := CkRest_AddQueryParam(rest,'ClientToken',CkJsonObject__stringOf(launch,'client_token'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set ClientToken.');
Exit;
end;
success := CkRest_AddQueryParam(rest,'ImageId',CkJsonObject__stringOf(launch,'image_id'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set ImageId.');
Exit;
end;
success := CkRest_AddQueryParam(rest,'InstanceType',CkJsonObject__stringOf(launch,'instance_type'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set InstanceType.');
Exit;
end;
success := CkRest_AddQueryParam(rest,'SubnetId',CkJsonObject__stringOf(launch,'subnet_id'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set SubnetId.');
Exit;
end;
success := CkRest_AddQueryParam(rest,'SecurityGroupId.1',CkJsonObject__stringOf(launch,'security_group_id'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set SecurityGroupId.1.');
Exit;
end;
success := CkRest_AddQueryParam(rest,'KeyName',CkJsonObject__stringOf(launch,'key_name'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set KeyName.');
Exit;
end;
success := CkRest_AddQueryParam(rest,'MinCount',CkJsonObject__stringOf(launch,'min_count'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set MinCount.');
Exit;
end;
success := CkRest_AddQueryParam(rest,'MaxCount',CkJsonObject__stringOf(launch,'max_count'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set MaxCount.');
Exit;
end;
success := CkRest_AddQueryParam(rest,'MetadataOptions.HttpTokens',CkJsonObject__stringOf(launch,'http_tokens'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set MetadataOptions.HttpTokens.');
Exit;
end;
success := CkRest_AddQueryParam(rest,'MetadataOptions.HttpEndpoint',CkJsonObject__stringOf(launch,'http_endpoint'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set MetadataOptions.HttpEndpoint.');
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) <> 'RunInstancesResponse') 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_NumChildrenAt(xml,'instancesSet') <> 1) then
begin
Memo1.Lines.Add('Expected exactly one launched instance; reconcile using the saved client token.');
Exit;
end;
if ((CkXml_HasChildWithTag(xml,'instancesSet|item|instanceId') <> True) or (CkXml__getChildContent(xml,'instancesSet|item|instanceId') = '')) then
begin
Memo1.Lines.Add('Missing or empty instancesSet|item|instanceId.');
Exit;
end;
instanceId := CkXml__getChildContent(xml,'instancesSet|item|instanceId');
Memo1.Lines.Add('Launch accepted for instance: ' + instanceId);
if (CkXml_HasChildWithTag(xml,'instancesSet|item|instanceState|name') = True) then
begin
Memo1.Lines.Add('State: ' + CkXml__getChildContent(xml,'instancesSet|item|instanceState|name'));
end;
success := CkJsonObject_UpdateString(launch,'instance_id',instanceId);
if (success <> True) then
begin
Memo1.Lines.Add('Could not record the returned instance ID; keep it privately.');
Exit;
end;
success := CkJsonObject_WriteFile(launch,launchFile);
if (success <> True) then
begin
Memo1.Lines.Add('Launch accepted but the result could not be saved. Record the ID before retrying.');
Exit;
end;
Memo1.Lines.Add('Saved instance ID. Wait for running state and health before use.');
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkFileAccess_Dispose(files);
CkJsonObject_Dispose(launch);
CkCrypt2_Dispose(uuid);
CkStringBuilder_Dispose(tokenText);