Sample code for 30+ languages & platforms
Xojo Plugin Requires Chilkat v11.6.0+

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.

RunInstances reference

Chilkat Xojo Plugin Downloads

Xojo Plugin
//  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 dryRun As Boolean
dryRun = True
//  Serialize access to this private file. Use a new file only for a NEW intended launch.
Dim launchFile As String
launchFile = "ec2-launch-request.json"
Dim files As New Chilkat.FileAccess
Dim launch As New Chilkat.JsonObject
launch.Strict = True
Dim fileStatus As Int32
fileStatus = files.FileExists3(launchFile)
If (fileStatus = 0) Then
    //  Replace these sample settings before the first run. Later runs use the saved file.
    Dim uuid As New Chilkat.Crypt2
    Dim clientToken As String
    clientToken = uuid.GenerateUuid()
    Dim tokenText As New Chilkat.StringBuilder
    success = tokenText.Append(clientToken)
    If (tokenText.Length <> 36) Then
        System.DebugLog("Could not generate a launch token.")
        Return
    End If

    success = launch.UpdateString("client_token",clientToken)
    If (success <> True) Then
        System.DebugLog("Could not save client token.")
        Return
    End If

    success = launch.UpdateString("region",region)
    If (success <> True) Then
        System.DebugLog("Could not save region.")
        Return
    End If

    success = launch.UpdateString("image_id","ami-0123456789abcdef0")
    If (success <> True) Then
        System.DebugLog("Could not prepare image_id.")
        Return
    End If

    success = launch.UpdateString("instance_type","t3.micro")
    If (success <> True) Then
        System.DebugLog("Could not prepare instance_type.")
        Return
    End If

    success = launch.UpdateString("subnet_id","subnet-0123456789abcdef0")
    If (success <> True) Then
        System.DebugLog("Could not prepare subnet_id.")
        Return
    End If

    success = launch.UpdateString("security_group_id","sg-0123456789abcdef0")
    If (success <> True) Then
        System.DebugLog("Could not prepare security_group_id.")
        Return
    End If

    success = launch.UpdateString("key_name","my-key-pair")
    If (success <> True) Then
        System.DebugLog("Could not prepare key_name.")
        Return
    End If

    success = launch.UpdateString("min_count","1")
    If (success <> True) Then
        System.DebugLog("Could not prepare min_count.")
        Return
    End If

    success = launch.UpdateString("max_count","1")
    If (success <> True) Then
        System.DebugLog("Could not prepare max_count.")
        Return
    End If

    success = launch.UpdateString("http_tokens","required")
    If (success <> True) Then
        System.DebugLog("Could not prepare http_tokens.")
        Return
    End If

    success = launch.UpdateString("http_endpoint","enabled")
    If (success <> True) Then
        System.DebugLog("Could not prepare http_endpoint.")
        Return
    End If

Else
    If (fileStatus <> 1) Then
        System.DebugLog("Launch path is inaccessible or is not a regular file.")
        Return
    End If

    success = launch.LoadFile(launchFile)
    If (success <> True) Then
        System.DebugLog("Could not load the saved launch request.")
        Return
    End If

End If

If ((launch.JsonTypeOf("region") <> 1) Or (launch.StringOf("region") = "")) Then
    System.DebugLog("Missing or invalid saved region.")
    Return
End If

If ((launch.JsonTypeOf("client_token") <> 1) Or (launch.StringOf("client_token") = "")) Then
    System.DebugLog("Missing or invalid saved client_token.")
    Return
End If

If ((launch.JsonTypeOf("image_id") <> 1) Or (launch.StringOf("image_id") = "")) Then
    System.DebugLog("Missing or invalid saved image_id.")
    Return
End If

If ((launch.JsonTypeOf("instance_type") <> 1) Or (launch.StringOf("instance_type") = "")) Then
    System.DebugLog("Missing or invalid saved instance_type.")
    Return
End If

If ((launch.JsonTypeOf("subnet_id") <> 1) Or (launch.StringOf("subnet_id") = "")) Then
    System.DebugLog("Missing or invalid saved subnet_id.")
    Return
End If

If ((launch.JsonTypeOf("security_group_id") <> 1) Or (launch.StringOf("security_group_id") = "")) Then
    System.DebugLog("Missing or invalid saved security_group_id.")
    Return
End If

If ((launch.JsonTypeOf("key_name") <> 1) Or (launch.StringOf("key_name") = "")) Then
    System.DebugLog("Missing or invalid saved key_name.")
    Return
End If

If ((launch.JsonTypeOf("min_count") <> 1) Or (launch.StringOf("min_count") = "")) Then
    System.DebugLog("Missing or invalid saved min_count.")
    Return
End If

If ((launch.JsonTypeOf("max_count") <> 1) Or (launch.StringOf("max_count") = "")) Then
    System.DebugLog("Missing or invalid saved max_count.")
    Return
End If

If ((launch.JsonTypeOf("http_tokens") <> 1) Or (launch.StringOf("http_tokens") = "")) Then
    System.DebugLog("Missing or invalid saved http_tokens.")
    Return
End If

If ((launch.JsonTypeOf("http_endpoint") <> 1) Or (launch.StringOf("http_endpoint") = "")) Then
    System.DebugLog("Missing or invalid saved http_endpoint.")
    Return
End If

If (launch.StringOf("region") <> region) Then
    System.DebugLog("Saved launch region differs; do not reuse this token in another region.")
    Return
End If

If ((launch.StringOf("min_count") <> "1") Or (launch.StringOf("max_count") <> "1")) Then
    System.DebugLog("This demonstration launches exactly one instance.")
    Return
End If

If (launch.HasMember("instance_id") = True) Then
    If ((launch.JsonTypeOf("instance_id") <> 1) Or (launch.StringOf("instance_id") = "")) Then
        System.DebugLog("Missing or invalid saved instance_id.")
        Return
    End If

    System.DebugLog("Launch already recorded for instance: " + launch.StringOf("instance_id"))
    System.DebugLog("No new launch request was sent.")
    Return
End If

//  Persist before sending, including dry runs. Never generate a new token for a retry.
success = launch.WriteFile(launchFile)
If (success <> True) Then
    System.DebugLog("Could not persist launch parameters; no launch sent.")
    Return
End If

success = rest.AddQueryParam("Action","RunInstances")
If (success <> True) Then
    System.DebugLog("Could not set Action.")
    Return
End If

success = rest.AddQueryParam("ClientToken",launch.StringOf("client_token"))
If (success <> True) Then
    System.DebugLog("Could not set ClientToken.")
    Return
End If

success = rest.AddQueryParam("ImageId",launch.StringOf("image_id"))
If (success <> True) Then
    System.DebugLog("Could not set ImageId.")
    Return
End If

success = rest.AddQueryParam("InstanceType",launch.StringOf("instance_type"))
If (success <> True) Then
    System.DebugLog("Could not set InstanceType.")
    Return
End If

success = rest.AddQueryParam("SubnetId",launch.StringOf("subnet_id"))
If (success <> True) Then
    System.DebugLog("Could not set SubnetId.")
    Return
End If

success = rest.AddQueryParam("SecurityGroupId.1",launch.StringOf("security_group_id"))
If (success <> True) Then
    System.DebugLog("Could not set SecurityGroupId.1.")
    Return
End If

success = rest.AddQueryParam("KeyName",launch.StringOf("key_name"))
If (success <> True) Then
    System.DebugLog("Could not set KeyName.")
    Return
End If

success = rest.AddQueryParam("MinCount",launch.StringOf("min_count"))
If (success <> True) Then
    System.DebugLog("Could not set MinCount.")
    Return
End If

success = rest.AddQueryParam("MaxCount",launch.StringOf("max_count"))
If (success <> True) Then
    System.DebugLog("Could not set MaxCount.")
    Return
End If

success = rest.AddQueryParam("MetadataOptions.HttpTokens",launch.StringOf("http_tokens"))
If (success <> True) Then
    System.DebugLog("Could not set MetadataOptions.HttpTokens.")
    Return
End If

success = rest.AddQueryParam("MetadataOptions.HttpEndpoint",launch.StringOf("http_endpoint"))
If (success <> True) Then
    System.DebugLog("Could not set MetadataOptions.HttpEndpoint.")
    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 <> "RunInstancesResponse") 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.NumChildrenAt("instancesSet") <> 1) Then
    System.DebugLog("Expected exactly one launched instance; reconcile using the saved client token.")
    Return
End If

If ((xml.HasChildWithTag("instancesSet|item|instanceId") <> True) Or (xml.GetChildContent("instancesSet|item|instanceId") = "")) Then
    System.DebugLog("Missing or empty instancesSet|item|instanceId.")
    Return
End If

Dim instanceId As String
instanceId = xml.GetChildContent("instancesSet|item|instanceId")
System.DebugLog("Launch accepted for instance: " + instanceId)
If (xml.HasChildWithTag("instancesSet|item|instanceState|name") = True) Then
    System.DebugLog("State: " + xml.GetChildContent("instancesSet|item|instanceState|name"))
End If

success = launch.UpdateString("instance_id",instanceId)
If (success <> True) Then
    System.DebugLog("Could not record the returned instance ID; keep it privately.")
    Return
End If

success = launch.WriteFile(launchFile)
If (success <> True) Then
    System.DebugLog("Launch accepted but the result could not be saved. Record the ID before retrying.")
    Return
End If

System.DebugLog("Saved instance ID. Wait for running state and health before use.")