Sample code for 30+ languages & platforms
DataFlex 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 DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoCredentials
    String sRegion
    Handle hoEndpoint
    Variant vAws
    Handle hoAws
    Handle hoRest
    Variant vConnection
    Handle hoConnection
    Handle hoXml
    String sResponseXml
    String sErrorCode
    Boolean iDryRun
    String sLaunchFile
    Handle hoFiles
    Handle hoLaunch
    Integer iFileStatus
    Handle hoUuid
    String sClientToken
    Handle hoTokenText
    String sInstanceId
    String sTemp1
    String sTemp2
    Integer iTemp1
    Boolean bTemp1

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    Move False To iSuccess
    //  Private configuration, not a file in public web content or source control.
    //  Load current IAM credentials authorized for the EC2 operation.
    Get Create (RefClass(cComChilkatJsonObject)) To hoCredentials
    If (Not(IsComObjectCreated(hoCredentials))) Begin
        Send CreateComObject of hoCredentials
    End
    Set ComStrict Of hoCredentials To True
    Get ComLoadFile Of hoCredentials "qa_data/aws/ec2.json" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not load private AWS credentials."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoCredentials "access_key" To iTemp1
    Get ComStringOf Of hoCredentials "access_key" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid access_key."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoCredentials "secret_key" To iTemp1
    Get ComStringOf Of hoCredentials "secret_key" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid secret_key."
        Procedure_Return
    End

    //  Set this once to the region containing the instances.
    Move "us-west-2" To sRegion
    Get Create (RefClass(cComChilkatStringBuilder)) To hoEndpoint
    If (Not(IsComObjectCreated(hoEndpoint))) Begin
        Send CreateComObject of hoEndpoint
    End
    Get ComAppend Of hoEndpoint "ec2." To iSuccess
    Get ComAppend Of hoEndpoint sRegion To iSuccess
    Get ComAppend Of hoEndpoint ".amazonaws.com" To iSuccess
    Get Create (RefClass(cComChilkatAuthAws)) To hoAws
    If (Not(IsComObjectCreated(hoAws))) Begin
        Send CreateComObject of hoAws
    End
    Get ComStringOf Of hoCredentials "access_key" To sTemp1
    Set ComAccessKey Of hoAws To sTemp1
    Get ComStringOf Of hoCredentials "secret_key" To sTemp1
    Set ComSecretKey Of hoAws To sTemp1
    Set ComRegion Of hoAws To sRegion
    Set ComServiceName Of hoAws To "ec2"
    Set ComSignatureVersion Of hoAws To 4
    Get Create (RefClass(cComChilkatRest)) To hoRest
    If (Not(IsComObjectCreated(hoRest))) Begin
        Send CreateComObject of hoRest
    End
    Set ComConnectTimeoutMs Of hoRest To 20000
    Set ComIdleTimeoutMs Of hoRest To 60000
    Get pvComObject of hoAws to vAws
    Get ComSetAuthAws Of hoRest vAws To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not configure AWS signing."
        Procedure_Return
    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.
    Get ComHasMember Of hoCredentials "session_token" To bTemp1
    If (bTemp1 = True) Begin
        Get ComJsonTypeOf Of hoCredentials "session_token" To iTemp1
        If (iTemp1 <> 1) Begin
            Showln "session_token must be a string."
            Procedure_Return
        End

        Get ComStringOf Of hoCredentials "session_token" To sTemp1
        If (sTemp1 <> "") Begin
            Get ComStringOf Of hoCredentials "session_token" To sTemp1
            Get ComAddQueryParam Of hoRest "X-Amz-Security-Token" sTemp1 To iSuccess
            If (iSuccess <> True) Begin
                Showln "Could not set the session-token parameter."
                Procedure_Return
            End

        End

    End

    //  Supply a Socket to explicitly enable TLS certificate verification.
    Get Create (RefClass(cComChilkatSocket)) To hoConnection
    If (Not(IsComObjectCreated(hoConnection))) Begin
        Send CreateComObject of hoConnection
    End
    Set ComRequireSslCertVerify Of hoConnection To True
    Set ComMaxReadIdleMs Of hoConnection To 60000
    Set ComMaxSendIdleMs Of hoConnection To 60000
    Get ComGetAsString Of hoEndpoint To sTemp1
    Get ComConnect Of hoConnection sTemp1 443 True 20000 To iSuccess
    If (iSuccess <> True) Begin
        Showln "TLS connection failed; inspect diagnostics privately."
        Procedure_Return
    End

    Get pvComObject of hoConnection to vConnection
    Get ComUseConnection Of hoRest vConnection True To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not attach the TLS connection."
        Procedure_Return
    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.
    Get Create (RefClass(cComChilkatXml)) To hoXml
    If (Not(IsComObjectCreated(hoXml))) Begin
        Send CreateComObject of hoXml
    End
    Set ComStrict Of hoXml To True
    Get ComAddQueryParam Of hoRest "Version" "2016-11-15" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set Version."
        Procedure_Return
    End

    Move "" To sResponseXml
    Move "" To sErrorCode
    Move True To iDryRun
    //  Serialize access to this private file. Use a new file only for a NEW intended launch.
    Move "ec2-launch-request.json" To sLaunchFile
    Get Create (RefClass(cComCkFileAccess)) To hoFiles
    If (Not(IsComObjectCreated(hoFiles))) Begin
        Send CreateComObject of hoFiles
    End
    Get Create (RefClass(cComChilkatJsonObject)) To hoLaunch
    If (Not(IsComObjectCreated(hoLaunch))) Begin
        Send CreateComObject of hoLaunch
    End
    Set ComStrict Of hoLaunch To True
    Get ComFileExists3 Of hoFiles sLaunchFile To iFileStatus
    If (iFileStatus = 0) Begin
        //  Replace these sample settings before the first run. Later runs use the saved file.
        Get Create (RefClass(cComChilkatCrypt2)) To hoUuid
        If (Not(IsComObjectCreated(hoUuid))) Begin
            Send CreateComObject of hoUuid
        End
        Get ComGenerateUuid Of hoUuid To sClientToken
        Get Create (RefClass(cComChilkatStringBuilder)) To hoTokenText
        If (Not(IsComObjectCreated(hoTokenText))) Begin
            Send CreateComObject of hoTokenText
        End
        Get ComAppend Of hoTokenText sClientToken To iSuccess
        Get ComLength Of hoTokenText To iTemp1
        If (iTemp1 <> 36) Begin
            Showln "Could not generate a launch token."
            Procedure_Return
        End

        Get ComUpdateString Of hoLaunch "client_token" sClientToken To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not save client token."
            Procedure_Return
        End

        Get ComUpdateString Of hoLaunch "region" sRegion To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not save region."
            Procedure_Return
        End

        Get ComUpdateString Of hoLaunch "image_id" "ami-0123456789abcdef0" To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not prepare image_id."
            Procedure_Return
        End

        Get ComUpdateString Of hoLaunch "instance_type" "t3.micro" To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not prepare instance_type."
            Procedure_Return
        End

        Get ComUpdateString Of hoLaunch "subnet_id" "subnet-0123456789abcdef0" To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not prepare subnet_id."
            Procedure_Return
        End

        Get ComUpdateString Of hoLaunch "security_group_id" "sg-0123456789abcdef0" To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not prepare security_group_id."
            Procedure_Return
        End

        Get ComUpdateString Of hoLaunch "key_name" "my-key-pair" To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not prepare key_name."
            Procedure_Return
        End

        Get ComUpdateString Of hoLaunch "min_count" "1" To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not prepare min_count."
            Procedure_Return
        End

        Get ComUpdateString Of hoLaunch "max_count" "1" To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not prepare max_count."
            Procedure_Return
        End

        Get ComUpdateString Of hoLaunch "http_tokens" "required" To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not prepare http_tokens."
            Procedure_Return
        End

        Get ComUpdateString Of hoLaunch "http_endpoint" "enabled" To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not prepare http_endpoint."
            Procedure_Return
        End

    End
    Else Begin
        If (iFileStatus <> 1) Begin
            Showln "Launch path is inaccessible or is not a regular file."
            Procedure_Return
        End

        Get ComLoadFile Of hoLaunch sLaunchFile To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not load the saved launch request."
            Procedure_Return
        End

    End

    Get ComJsonTypeOf Of hoLaunch "region" To iTemp1
    Get ComStringOf Of hoLaunch "region" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid saved region."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoLaunch "client_token" To iTemp1
    Get ComStringOf Of hoLaunch "client_token" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid saved client_token."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoLaunch "image_id" To iTemp1
    Get ComStringOf Of hoLaunch "image_id" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid saved image_id."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoLaunch "instance_type" To iTemp1
    Get ComStringOf Of hoLaunch "instance_type" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid saved instance_type."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoLaunch "subnet_id" To iTemp1
    Get ComStringOf Of hoLaunch "subnet_id" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid saved subnet_id."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoLaunch "security_group_id" To iTemp1
    Get ComStringOf Of hoLaunch "security_group_id" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid saved security_group_id."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoLaunch "key_name" To iTemp1
    Get ComStringOf Of hoLaunch "key_name" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid saved key_name."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoLaunch "min_count" To iTemp1
    Get ComStringOf Of hoLaunch "min_count" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid saved min_count."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoLaunch "max_count" To iTemp1
    Get ComStringOf Of hoLaunch "max_count" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid saved max_count."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoLaunch "http_tokens" To iTemp1
    Get ComStringOf Of hoLaunch "http_tokens" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid saved http_tokens."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoLaunch "http_endpoint" To iTemp1
    Get ComStringOf Of hoLaunch "http_endpoint" To sTemp1
    If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
        Showln "Missing or invalid saved http_endpoint."
        Procedure_Return
    End

    Get ComStringOf Of hoLaunch "region" To sTemp1
    If (sTemp1 <> sRegion) Begin
        Showln "Saved launch region differs; do not reuse this token in another region."
        Procedure_Return
    End

    Get ComStringOf Of hoLaunch "min_count" To sTemp1
    Get ComStringOf Of hoLaunch "max_count" To sTemp2
    If ((sTemp1 <> "1") Or (sTemp2 <> "1")) Begin
        Showln "This demonstration launches exactly one instance."
        Procedure_Return
    End

    Get ComHasMember Of hoLaunch "instance_id" To bTemp1
    If (bTemp1 = True) Begin
        Get ComJsonTypeOf Of hoLaunch "instance_id" To iTemp1
        Get ComStringOf Of hoLaunch "instance_id" To sTemp1
        If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
            Showln "Missing or invalid saved instance_id."
            Procedure_Return
        End

        Get ComStringOf Of hoLaunch "instance_id" To sTemp1
        Showln "Launch already recorded for instance: " sTemp1
        Showln "No new launch request was sent."
        Procedure_Return
    End

    //  Persist before sending, including dry runs. Never generate a new token for a retry.
    Get ComWriteFile Of hoLaunch sLaunchFile To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not persist launch parameters; no launch sent."
        Procedure_Return
    End

    Get ComAddQueryParam Of hoRest "Action" "RunInstances" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set Action."
        Procedure_Return
    End

    Get ComStringOf Of hoLaunch "client_token" To sTemp1
    Get ComAddQueryParam Of hoRest "ClientToken" sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set ClientToken."
        Procedure_Return
    End

    Get ComStringOf Of hoLaunch "image_id" To sTemp1
    Get ComAddQueryParam Of hoRest "ImageId" sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set ImageId."
        Procedure_Return
    End

    Get ComStringOf Of hoLaunch "instance_type" To sTemp1
    Get ComAddQueryParam Of hoRest "InstanceType" sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set InstanceType."
        Procedure_Return
    End

    Get ComStringOf Of hoLaunch "subnet_id" To sTemp1
    Get ComAddQueryParam Of hoRest "SubnetId" sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set SubnetId."
        Procedure_Return
    End

    Get ComStringOf Of hoLaunch "security_group_id" To sTemp1
    Get ComAddQueryParam Of hoRest "SecurityGroupId.1" sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set SecurityGroupId.1."
        Procedure_Return
    End

    Get ComStringOf Of hoLaunch "key_name" To sTemp1
    Get ComAddQueryParam Of hoRest "KeyName" sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set KeyName."
        Procedure_Return
    End

    Get ComStringOf Of hoLaunch "min_count" To sTemp1
    Get ComAddQueryParam Of hoRest "MinCount" sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set MinCount."
        Procedure_Return
    End

    Get ComStringOf Of hoLaunch "max_count" To sTemp1
    Get ComAddQueryParam Of hoRest "MaxCount" sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set MaxCount."
        Procedure_Return
    End

    Get ComStringOf Of hoLaunch "http_tokens" To sTemp1
    Get ComAddQueryParam Of hoRest "MetadataOptions.HttpTokens" sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set MetadataOptions.HttpTokens."
        Procedure_Return
    End

    Get ComStringOf Of hoLaunch "http_endpoint" To sTemp1
    Get ComAddQueryParam Of hoRest "MetadataOptions.HttpEndpoint" sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not set MetadataOptions.HttpEndpoint."
        Procedure_Return
    End

    If (iDryRun = True) Begin
        Get ComAddQueryParam Of hoRest "DryRun" "true" To iSuccess
        If (iSuccess <> True) Begin
            Showln "Could not set DryRun."
            Procedure_Return
        End

    End

    Get ComFullRequestNoBody Of hoRest "GET" "/" To sResponseXml
    Get ComLastMethodSuccess Of hoRest To bTemp1
    If (bTemp1 <> True) Begin
        Showln "Request did not complete; inspect diagnostics privately."
        //  The operation might already have been accepted. Check state before retrying.
        Procedure_Return
    End

    Get ComLoadXml Of hoXml sResponseXml To iSuccess
    Get ComResponseStatusCode Of hoRest To iTemp1
    If (iTemp1 <> 200) Begin
        Get ComResponseStatusCode Of hoRest To iTemp1
        Showln "EC2 HTTP status: " iTemp1
        If (iSuccess = True) Begin
            Get ComHasChildWithTag Of hoXml "Errors|Error|Code" To bTemp1
            If (bTemp1 = True) Begin
                Get ComGetChildContent Of hoXml "Errors|Error|Code" To sErrorCode
                If ((iDryRun = True) And (sErrorCode = "DryRunOperation")) Begin
                    Showln "Dry run authorized. No resource was changed."
                    Showln "Set dryRun to false only when ready to perform the operation."
                    Procedure_Return
                End

                Showln "AWS error code: " sErrorCode
            End

            Get ComHasChildWithTag Of hoXml "RequestID" To bTemp1
            If (bTemp1 = True) Begin
                Get ComGetChildContent Of hoXml "RequestID" To sTemp1
                Showln "AWS request ID: " sTemp1
            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.
        Procedure_Return
    End

    If (iSuccess <> True) Begin
        Showln "Expected a well-formed XML response."
        Procedure_Return
    End

    Get ComTag Of hoXml To sTemp1
    If (sTemp1 <> "RunInstancesResponse") Begin
        Showln "Unexpected EC2 response element."
        Procedure_Return
    End

    If (iDryRun = True) Begin
        Showln "Unexpected HTTP 200 for a dry run; do not treat this as authorization to proceed."
        Procedure_Return
    End

    Get ComHasChildWithTag Of hoXml "requestId" To bTemp1
    Get ComGetChildContent Of hoXml "requestId" To sTemp1
    If ((bTemp1 <> True) Or (sTemp1 = "")) Begin
        Showln "Missing or empty requestId."
        Procedure_Return
    End

    Get ComGetChildContent Of hoXml "requestId" To sTemp1
    Showln "AWS request ID: " sTemp1
    Get ComNumChildrenAt Of hoXml "instancesSet" To iTemp1
    If (iTemp1 <> 1) Begin
        Showln "Expected exactly one launched instance; reconcile using the saved client token."
        Procedure_Return
    End

    Get ComHasChildWithTag Of hoXml "instancesSet|item|instanceId" To bTemp1
    Get ComGetChildContent Of hoXml "instancesSet|item|instanceId" To sTemp1
    If ((bTemp1 <> True) Or (sTemp1 = "")) Begin
        Showln "Missing or empty instancesSet|item|instanceId."
        Procedure_Return
    End

    Get ComGetChildContent Of hoXml "instancesSet|item|instanceId" To sInstanceId
    Showln "Launch accepted for instance: " sInstanceId
    Get ComHasChildWithTag Of hoXml "instancesSet|item|instanceState|name" To bTemp1
    If (bTemp1 = True) Begin
        Get ComGetChildContent Of hoXml "instancesSet|item|instanceState|name" To sTemp1
        Showln "State: " sTemp1
    End

    Get ComUpdateString Of hoLaunch "instance_id" sInstanceId To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not record the returned instance ID; keep it privately."
        Procedure_Return
    End

    Get ComWriteFile Of hoLaunch sLaunchFile To iSuccess
    If (iSuccess <> True) Begin
        Showln "Launch accepted but the result could not be saved. Record the ID before retrying."
        Procedure_Return
    End

    Showln "Saved instance ID. Wait for running state and health before use."


End_Procedure