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

PowerBuilder
integer li_rc
long li_Success
oleobject loo_Credentials
string ls_Region
oleobject loo_Endpoint
oleobject loo_Aws
oleobject loo_Rest
oleobject loo_Connection
oleobject loo_Xml
string ls_ResponseXml
string ls_ErrorCode
long li_DryRun
string ls_LaunchFile
oleobject loo_Files
oleobject loo_Launch
long li_FileStatus
oleobject loo_Uuid
string ls_ClientToken
oleobject loo_TokenText
string ls_InstanceId

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
li_Success = 0
//  Private configuration, not a file in public web content or source control.
//  Load current IAM credentials authorized for the EC2 operation.
loo_Credentials = create oleobject
li_rc = loo_Credentials.ConnectToNewObject("Chilkat.JsonObject")
if li_rc < 0 then
    destroy loo_Credentials
    MessageBox("Error","Connecting to COM object failed")
    return
end if
loo_Credentials.Strict = 1
li_Success = loo_Credentials.LoadFile("qa_data/aws/ec2.json")
if li_Success <> 1 then
    Write-Debug "Could not load private AWS credentials."
    destroy loo_Credentials
    return
end if

if (loo_Credentials.JsonTypeOf("access_key") <> 1) OR (loo_Credentials.StringOf("access_key") = "") then
    Write-Debug "Missing or invalid access_key."
    destroy loo_Credentials
    return
end if

if (loo_Credentials.JsonTypeOf("secret_key") <> 1) OR (loo_Credentials.StringOf("secret_key") = "") then
    Write-Debug "Missing or invalid secret_key."
    destroy loo_Credentials
    return
end if

//  Set this once to the region containing the instances.
ls_Region = "us-west-2"
loo_Endpoint = create oleobject
li_rc = loo_Endpoint.ConnectToNewObject("Chilkat.StringBuilder")

loo_Endpoint.Append("ec2.")
loo_Endpoint.Append(ls_Region)
loo_Endpoint.Append(".amazonaws.com")
loo_Aws = create oleobject
li_rc = loo_Aws.ConnectToNewObject("Chilkat.AuthAws")

loo_Aws.AccessKey = loo_Credentials.StringOf("access_key")
loo_Aws.SecretKey = loo_Credentials.StringOf("secret_key")
loo_Aws.Region = ls_Region
loo_Aws.ServiceName = "ec2"
loo_Aws.SignatureVersion = 4
loo_Rest = create oleobject
li_rc = loo_Rest.ConnectToNewObject("Chilkat.Rest")

loo_Rest.ConnectTimeoutMs = 20000
loo_Rest.IdleTimeoutMs = 60000
li_Success = loo_Rest.SetAuthAws(loo_Aws)
if li_Success <> 1 then
    Write-Debug "Could not configure AWS signing."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    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 loo_Credentials.HasMember("session_token") = 1 then
    if loo_Credentials.JsonTypeOf("session_token") <> 1 then
        Write-Debug "session_token must be a string."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        return
    end if

    if loo_Credentials.StringOf("session_token") <> "" then
        li_Success = loo_Rest.AddQueryParam("X-Amz-Security-Token",loo_Credentials.StringOf("session_token"))
        if li_Success <> 1 then
            Write-Debug "Could not set the session-token parameter."
            destroy loo_Credentials
            destroy loo_Endpoint
            destroy loo_Aws
            destroy loo_Rest
            return
        end if

    end if

end if

//  Supply a Socket to explicitly enable TLS certificate verification.
loo_Connection = create oleobject
li_rc = loo_Connection.ConnectToNewObject("Chilkat.Socket")

loo_Connection.RequireSslCertVerify = 1
loo_Connection.MaxReadIdleMs = 60000
loo_Connection.MaxSendIdleMs = 60000
li_Success = loo_Connection.Connect(loo_Endpoint.GetAsString(),443,1,20000)
if li_Success <> 1 then
    Write-Debug "TLS connection failed; inspect diagnostics privately."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    return
end if

li_Success = loo_Rest.UseConnection(loo_Connection,1)
if li_Success <> 1 then
    Write-Debug "Could not attach the TLS connection."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_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.
loo_Xml = create oleobject
li_rc = loo_Xml.ConnectToNewObject("Chilkat.Xml")

loo_Xml.Strict = 1
li_Success = loo_Rest.AddQueryParam("Version","2016-11-15")
if li_Success <> 1 then
    Write-Debug "Could not set Version."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    return
end if

ls_ResponseXml = ""
ls_ErrorCode = ""
li_DryRun = 1
//  Serialize access to this private file. Use a new file only for a NEW intended launch.
ls_LaunchFile = "ec2-launch-request.json"
loo_Files = create oleobject
li_rc = loo_Files.ConnectToNewObject("Chilkat.FileAccess")

loo_Launch = create oleobject
li_rc = loo_Launch.ConnectToNewObject("Chilkat.JsonObject")

loo_Launch.Strict = 1
li_FileStatus = loo_Files.FileExists3(ls_LaunchFile)
if li_FileStatus = 0 then
    //  Replace these sample settings before the first run. Later runs use the saved file.
    loo_Uuid = create oleobject
    li_rc = loo_Uuid.ConnectToNewObject("Chilkat.Crypt2")

    ls_ClientToken = loo_Uuid.GenerateUuid()
    loo_TokenText = create oleobject
    li_rc = loo_TokenText.ConnectToNewObject("Chilkat.StringBuilder")

    loo_TokenText.Append(ls_ClientToken)
    if loo_TokenText.Length <> 36 then
        Write-Debug "Could not generate a launch token."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_Files
        destroy loo_Launch
        destroy loo_Uuid
        destroy loo_TokenText
        return
    end if

    li_Success = loo_Launch.UpdateString("client_token",ls_ClientToken)
    if li_Success <> 1 then
        Write-Debug "Could not save client token."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_Files
        destroy loo_Launch
        destroy loo_Uuid
        destroy loo_TokenText
        return
    end if

    li_Success = loo_Launch.UpdateString("region",ls_Region)
    if li_Success <> 1 then
        Write-Debug "Could not save region."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_Files
        destroy loo_Launch
        destroy loo_Uuid
        destroy loo_TokenText
        return
    end if

    li_Success = loo_Launch.UpdateString("image_id","ami-0123456789abcdef0")
    if li_Success <> 1 then
        Write-Debug "Could not prepare image_id."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_Files
        destroy loo_Launch
        destroy loo_Uuid
        destroy loo_TokenText
        return
    end if

    li_Success = loo_Launch.UpdateString("instance_type","t3.micro")
    if li_Success <> 1 then
        Write-Debug "Could not prepare instance_type."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_Files
        destroy loo_Launch
        destroy loo_Uuid
        destroy loo_TokenText
        return
    end if

    li_Success = loo_Launch.UpdateString("subnet_id","subnet-0123456789abcdef0")
    if li_Success <> 1 then
        Write-Debug "Could not prepare subnet_id."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_Files
        destroy loo_Launch
        destroy loo_Uuid
        destroy loo_TokenText
        return
    end if

    li_Success = loo_Launch.UpdateString("security_group_id","sg-0123456789abcdef0")
    if li_Success <> 1 then
        Write-Debug "Could not prepare security_group_id."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_Files
        destroy loo_Launch
        destroy loo_Uuid
        destroy loo_TokenText
        return
    end if

    li_Success = loo_Launch.UpdateString("key_name","my-key-pair")
    if li_Success <> 1 then
        Write-Debug "Could not prepare key_name."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_Files
        destroy loo_Launch
        destroy loo_Uuid
        destroy loo_TokenText
        return
    end if

    li_Success = loo_Launch.UpdateString("min_count","1")
    if li_Success <> 1 then
        Write-Debug "Could not prepare min_count."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_Files
        destroy loo_Launch
        destroy loo_Uuid
        destroy loo_TokenText
        return
    end if

    li_Success = loo_Launch.UpdateString("max_count","1")
    if li_Success <> 1 then
        Write-Debug "Could not prepare max_count."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_Files
        destroy loo_Launch
        destroy loo_Uuid
        destroy loo_TokenText
        return
    end if

    li_Success = loo_Launch.UpdateString("http_tokens","required")
    if li_Success <> 1 then
        Write-Debug "Could not prepare http_tokens."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_Files
        destroy loo_Launch
        destroy loo_Uuid
        destroy loo_TokenText
        return
    end if

    li_Success = loo_Launch.UpdateString("http_endpoint","enabled")
    if li_Success <> 1 then
        Write-Debug "Could not prepare http_endpoint."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_Files
        destroy loo_Launch
        destroy loo_Uuid
        destroy loo_TokenText
        return
    end if

else
    if li_FileStatus <> 1 then
        Write-Debug "Launch path is inaccessible or is not a regular file."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_Files
        destroy loo_Launch
        destroy loo_Uuid
        destroy loo_TokenText
        return
    end if

    li_Success = loo_Launch.LoadFile(ls_LaunchFile)
    if li_Success <> 1 then
        Write-Debug "Could not load the saved launch request."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_Files
        destroy loo_Launch
        destroy loo_Uuid
        destroy loo_TokenText
        return
    end if

end if

if (loo_Launch.JsonTypeOf("region") <> 1) OR (loo_Launch.StringOf("region") = "") then
    Write-Debug "Missing or invalid saved region."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if (loo_Launch.JsonTypeOf("client_token") <> 1) OR (loo_Launch.StringOf("client_token") = "") then
    Write-Debug "Missing or invalid saved client_token."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if (loo_Launch.JsonTypeOf("image_id") <> 1) OR (loo_Launch.StringOf("image_id") = "") then
    Write-Debug "Missing or invalid saved image_id."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if (loo_Launch.JsonTypeOf("instance_type") <> 1) OR (loo_Launch.StringOf("instance_type") = "") then
    Write-Debug "Missing or invalid saved instance_type."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if (loo_Launch.JsonTypeOf("subnet_id") <> 1) OR (loo_Launch.StringOf("subnet_id") = "") then
    Write-Debug "Missing or invalid saved subnet_id."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if (loo_Launch.JsonTypeOf("security_group_id") <> 1) OR (loo_Launch.StringOf("security_group_id") = "") then
    Write-Debug "Missing or invalid saved security_group_id."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if (loo_Launch.JsonTypeOf("key_name") <> 1) OR (loo_Launch.StringOf("key_name") = "") then
    Write-Debug "Missing or invalid saved key_name."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if (loo_Launch.JsonTypeOf("min_count") <> 1) OR (loo_Launch.StringOf("min_count") = "") then
    Write-Debug "Missing or invalid saved min_count."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if (loo_Launch.JsonTypeOf("max_count") <> 1) OR (loo_Launch.StringOf("max_count") = "") then
    Write-Debug "Missing or invalid saved max_count."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if (loo_Launch.JsonTypeOf("http_tokens") <> 1) OR (loo_Launch.StringOf("http_tokens") = "") then
    Write-Debug "Missing or invalid saved http_tokens."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if (loo_Launch.JsonTypeOf("http_endpoint") <> 1) OR (loo_Launch.StringOf("http_endpoint") = "") then
    Write-Debug "Missing or invalid saved http_endpoint."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if loo_Launch.StringOf("region") <> ls_Region then
    Write-Debug "Saved launch region differs; do not reuse this token in another region."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if (loo_Launch.StringOf("min_count") <> "1") OR (loo_Launch.StringOf("max_count") <> "1") then
    Write-Debug "This demonstration launches exactly one instance."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if loo_Launch.HasMember("instance_id") = 1 then
    if (loo_Launch.JsonTypeOf("instance_id") <> 1) OR (loo_Launch.StringOf("instance_id") = "") then
        Write-Debug "Missing or invalid saved instance_id."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_Files
        destroy loo_Launch
        destroy loo_Uuid
        destroy loo_TokenText
        return
    end if

    Write-Debug "Launch already recorded for instance: " + loo_Launch.StringOf("instance_id")
    Write-Debug "No new launch request was sent."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

//  Persist before sending, including dry runs. Never generate a new token for a retry.
li_Success = loo_Launch.WriteFile(ls_LaunchFile)
if li_Success <> 1 then
    Write-Debug "Could not persist launch parameters; no launch sent."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

li_Success = loo_Rest.AddQueryParam("Action","RunInstances")
if li_Success <> 1 then
    Write-Debug "Could not set Action."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

li_Success = loo_Rest.AddQueryParam("ClientToken",loo_Launch.StringOf("client_token"))
if li_Success <> 1 then
    Write-Debug "Could not set ClientToken."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

li_Success = loo_Rest.AddQueryParam("ImageId",loo_Launch.StringOf("image_id"))
if li_Success <> 1 then
    Write-Debug "Could not set ImageId."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

li_Success = loo_Rest.AddQueryParam("InstanceType",loo_Launch.StringOf("instance_type"))
if li_Success <> 1 then
    Write-Debug "Could not set InstanceType."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

li_Success = loo_Rest.AddQueryParam("SubnetId",loo_Launch.StringOf("subnet_id"))
if li_Success <> 1 then
    Write-Debug "Could not set SubnetId."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

li_Success = loo_Rest.AddQueryParam("SecurityGroupId.1",loo_Launch.StringOf("security_group_id"))
if li_Success <> 1 then
    Write-Debug "Could not set SecurityGroupId.1."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

li_Success = loo_Rest.AddQueryParam("KeyName",loo_Launch.StringOf("key_name"))
if li_Success <> 1 then
    Write-Debug "Could not set KeyName."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

li_Success = loo_Rest.AddQueryParam("MinCount",loo_Launch.StringOf("min_count"))
if li_Success <> 1 then
    Write-Debug "Could not set MinCount."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

li_Success = loo_Rest.AddQueryParam("MaxCount",loo_Launch.StringOf("max_count"))
if li_Success <> 1 then
    Write-Debug "Could not set MaxCount."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

li_Success = loo_Rest.AddQueryParam("MetadataOptions.HttpTokens",loo_Launch.StringOf("http_tokens"))
if li_Success <> 1 then
    Write-Debug "Could not set MetadataOptions.HttpTokens."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

li_Success = loo_Rest.AddQueryParam("MetadataOptions.HttpEndpoint",loo_Launch.StringOf("http_endpoint"))
if li_Success <> 1 then
    Write-Debug "Could not set MetadataOptions.HttpEndpoint."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if li_DryRun = 1 then
    li_Success = loo_Rest.AddQueryParam("DryRun","true")
    if li_Success <> 1 then
        Write-Debug "Could not set DryRun."
        destroy loo_Credentials
        destroy loo_Endpoint
        destroy loo_Aws
        destroy loo_Rest
        destroy loo_Connection
        destroy loo_Xml
        destroy loo_Files
        destroy loo_Launch
        destroy loo_Uuid
        destroy loo_TokenText
        return
    end if

end if

ls_ResponseXml = loo_Rest.FullRequestNoBody("GET","/")
if loo_Rest.LastMethodSuccess <> 1 then
    Write-Debug "Request did not complete; inspect diagnostics privately."
    //  The operation might already have been accepted. Check state before retrying.
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

li_Success = loo_Xml.LoadXml(ls_ResponseXml)
if loo_Rest.ResponseStatusCode <> 200 then
    Write-Debug "EC2 HTTP status: " + string(loo_Rest.ResponseStatusCode)
    if li_Success = 1 then
        if loo_Xml.HasChildWithTag("Errors|Error|Code") = 1 then
            ls_ErrorCode = loo_Xml.GetChildContent("Errors|Error|Code")
            if (li_DryRun = 1) AND (ls_ErrorCode = "DryRunOperation") then
                Write-Debug "Dry run authorized. No resource was changed."
                Write-Debug "Set dryRun to false only when ready to perform the operation."
                destroy loo_Credentials
                destroy loo_Endpoint
                destroy loo_Aws
                destroy loo_Rest
                destroy loo_Connection
                destroy loo_Xml
                destroy loo_Files
                destroy loo_Launch
                destroy loo_Uuid
                destroy loo_TokenText
                return
            end if

            Write-Debug "AWS error code: " + ls_ErrorCode
        end if

        if loo_Xml.HasChildWithTag("RequestID") = 1 then
            Write-Debug "AWS request ID: " + loo_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.
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if li_Success <> 1 then
    Write-Debug "Expected a well-formed XML response."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if loo_Xml.Tag <> "RunInstancesResponse" then
    Write-Debug "Unexpected EC2 response element."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if li_DryRun = 1 then
    Write-Debug "Unexpected HTTP 200 for a dry run; do not treat this as authorization to proceed."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if (loo_Xml.HasChildWithTag("requestId") <> 1) OR (loo_Xml.GetChildContent("requestId") = "") then
    Write-Debug "Missing or empty requestId."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

Write-Debug "AWS request ID: " + loo_Xml.GetChildContent("requestId")
if loo_Xml.NumChildrenAt("instancesSet") <> 1 then
    Write-Debug "Expected exactly one launched instance; reconcile using the saved client token."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

if (loo_Xml.HasChildWithTag("instancesSet|item|instanceId") <> 1) OR (loo_Xml.GetChildContent("instancesSet|item|instanceId") = "") then
    Write-Debug "Missing or empty instancesSet|item|instanceId."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

ls_InstanceId = loo_Xml.GetChildContent("instancesSet|item|instanceId")
Write-Debug "Launch accepted for instance: " + ls_InstanceId
if loo_Xml.HasChildWithTag("instancesSet|item|instanceState|name") = 1 then
    Write-Debug "State: " + loo_Xml.GetChildContent("instancesSet|item|instanceState|name")
end if

li_Success = loo_Launch.UpdateString("instance_id",ls_InstanceId)
if li_Success <> 1 then
    Write-Debug "Could not record the returned instance ID; keep it privately."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

li_Success = loo_Launch.WriteFile(ls_LaunchFile)
if li_Success <> 1 then
    Write-Debug "Launch accepted but the result could not be saved. Record the ID before retrying."
    destroy loo_Credentials
    destroy loo_Endpoint
    destroy loo_Aws
    destroy loo_Rest
    destroy loo_Connection
    destroy loo_Xml
    destroy loo_Files
    destroy loo_Launch
    destroy loo_Uuid
    destroy loo_TokenText
    return
end if

Write-Debug "Saved instance ID. Wait for running state and health before use."


destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Xml
destroy loo_Files
destroy loo_Launch
destroy loo_Uuid
destroy loo_TokenText