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

Amazon EC2: Start Stopped Instances

See more Amazon EC2 Examples

Start previously stopped, EBS-backed instances. This does not create new instances; launching uses RunInstances. Live mode resumes instance usage charges. A successful response supplies previous/current states for each returned ID. A state such as pending means startup is still underway.

Poll DescribeInstances with a delay and deadline for running, then check instance health and application readiness. A running state alone is not a health check. An automatically assigned public IPv4 address can change after stop/start; use the newly reported address or an appropriate stable endpoint.

Defaults to a permission check: dryRun=true returns the expected DryRunOperation error when authorized; the code handles it explicitly and does not automatically send a live request. UnauthorizedOperation indicates missing permission. A successful dry run is not proof that a future live operation will succeed. Set dryRun to false deliberately to perform the operation. Add InstanceId.2, InstanceId.3, etc. for more instances; keep every ID as a string.

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.

Required IAM action: ec2:StartInstances. Restrict changes to the intended instance resources.

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.

AWS StartInstances reference

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkAuthAws.pb"
IncludeFile "CkJsonObject.pb"
IncludeFile "CkSocket.pb"
IncludeFile "CkXml.pb"
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkRest.pb"

Procedure ChilkatExample()

    ;  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success.i = 0
    ;  Private configuration, not a file in public web content or source control.
    ;  Load current IAM credentials authorized for the EC2 operation.
    credentials.i = CkJsonObject::ckCreate()
    If credentials.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkJsonObject::setCkStrict(credentials, 1)
    success = CkJsonObject::ckLoadFile(credentials,"qa_data/aws/ec2.json")
    If success <> 1
        Debug "Could not load private AWS credentials."
        CkJsonObject::ckDispose(credentials)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(credentials,"access_key") <> 1) OR (CkJsonObject::ckStringOf(credentials,"access_key") = "")
        Debug "Missing or invalid access_key."
        CkJsonObject::ckDispose(credentials)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(credentials,"secret_key") <> 1) OR (CkJsonObject::ckStringOf(credentials,"secret_key") = "")
        Debug "Missing or invalid secret_key."
        CkJsonObject::ckDispose(credentials)
        ProcedureReturn
    EndIf

    ;  Set this once to the region containing the instances.
    region.s = "us-west-2"
    endpoint.i = CkStringBuilder::ckCreate()
    If endpoint.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStringBuilder::ckAppend(endpoint,"ec2.")
    CkStringBuilder::ckAppend(endpoint,region)
    CkStringBuilder::ckAppend(endpoint,".amazonaws.com")
    aws.i = CkAuthAws::ckCreate()
    If aws.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkAuthAws::setCkAccessKey(aws, CkJsonObject::ckStringOf(credentials,"access_key"))
    CkAuthAws::setCkSecretKey(aws, CkJsonObject::ckStringOf(credentials,"secret_key"))
    CkAuthAws::setCkRegion(aws, region)
    CkAuthAws::setCkServiceName(aws, "ec2")
    CkAuthAws::setCkSignatureVersion(aws, 4)
    rest.i = CkRest::ckCreate()
    If rest.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkRest::setCkConnectTimeoutMs(rest, 20000)
    CkRest::setCkIdleTimeoutMs(rest, 60000)
    success = CkRest::ckSetAuthAws(rest,aws)
    If success <> 1
        Debug "Could not configure AWS signing."
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        ProcedureReturn
    EndIf

    ;  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::ckHasMember(credentials,"session_token") = 1
        If CkJsonObject::ckJsonTypeOf(credentials,"session_token") <> 1
            Debug "session_token must be a string."
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(endpoint)
            CkAuthAws::ckDispose(aws)
            CkRest::ckDispose(rest)
            ProcedureReturn
        EndIf

        If CkJsonObject::ckStringOf(credentials,"session_token") <> ""
            success = CkRest::ckAddQueryParam(rest,"X-Amz-Security-Token",CkJsonObject::ckStringOf(credentials,"session_token"))
            If success <> 1
                Debug "Could not set the session-token parameter."
                CkJsonObject::ckDispose(credentials)
                CkStringBuilder::ckDispose(endpoint)
                CkAuthAws::ckDispose(aws)
                CkRest::ckDispose(rest)
                ProcedureReturn
            EndIf

        EndIf

    EndIf

    ;  Supply a Socket to explicitly enable TLS certificate verification.
    connection.i = CkSocket::ckCreate()
    If connection.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkSocket::setCkRequireSslCertVerify(connection, 1)
    CkSocket::setCkMaxReadIdleMs(connection, 60000)
    CkSocket::setCkMaxSendIdleMs(connection, 60000)
    success = CkSocket::ckConnect(connection,CkStringBuilder::ckGetAsString(endpoint),443,1,20000)
    If success <> 1
        Debug "TLS connection failed; inspect diagnostics privately."
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        ProcedureReturn
    EndIf

    success = CkRest::ckUseConnection(rest,connection,1)
    If success <> 1
        Debug "Could not attach the TLS connection."
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        ProcedureReturn
    EndIf

    ;  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.i = CkXml::ckCreate()
    If xml.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkXml::setCkStrict(xml, 1)
    success = CkRest::ckAddQueryParam(rest,"Version","2016-11-15")
    If success <> 1
        Debug "Could not set Version."
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        ProcedureReturn
    EndIf

    ;  Keep IDs as strings. Choose an instance in the configured account and region.
    instanceId.s = "i-1234567890abcdef0"
    ;  Change to false only when ready for the live operation described above.
    dryRun.i = 1
    success = CkRest::ckAddQueryParam(rest,"Action","StartInstances")
    If success <> 1
        Debug "Could not set Action."
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        ProcedureReturn
    EndIf

    success = CkRest::ckAddQueryParam(rest,"InstanceId.1",instanceId)
    If success <> 1
        Debug "Could not set InstanceId.1."
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        ProcedureReturn
    EndIf

    If dryRun = 1
        success = CkRest::ckAddQueryParam(rest,"DryRun","true")
        If success <> 1
            Debug "Could not set DryRun."
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(endpoint)
            CkAuthAws::ckDispose(aws)
            CkRest::ckDispose(rest)
            CkSocket::ckDispose(connection)
            CkXml::ckDispose(xml)
            ProcedureReturn
        EndIf

    EndIf

    responseXml.s = CkRest::ckFullRequestNoBody(rest,"GET","/")
    If CkRest::ckLastMethodSuccess(rest) <> 1
        Debug "Request did not complete; inspect diagnostics privately."
        ;  The operation might already have been accepted. Check state before retrying.
        ;  Do not blindly repeat a reboot after a timeout.
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        ProcedureReturn
    EndIf

    success = CkXml::ckLoadXml(xml,responseXml)
    If CkRest::ckResponseStatusCode(rest) <> 200
        Debug "EC2 HTTP status: " + Str(CkRest::ckResponseStatusCode(rest))
        If success = 1
            If CkXml::ckHasChildWithTag(xml,"Errors|Error|Code") = 1
                errorCode.s = CkXml::ckGetChildContent(xml,"Errors|Error|Code")
                If (dryRun = 1) AND (errorCode = "DryRunOperation")
                    Debug "Dry run authorized. No instance was changed."
                    Debug "Set dryRun to false only when ready to perform the operation."
                    CkJsonObject::ckDispose(credentials)
                    CkStringBuilder::ckDispose(endpoint)
                    CkAuthAws::ckDispose(aws)
                    CkRest::ckDispose(rest)
                    CkSocket::ckDispose(connection)
                    CkXml::ckDispose(xml)
                    ProcedureReturn
                EndIf

                Debug "AWS error code: " + errorCode
            EndIf

            If CkXml::ckHasChildWithTag(xml,"RequestID") = 1
                Debug "AWS request ID: " + CkXml::ckGetChildContent(xml,"RequestID")
            EndIf

        EndIf

        ;  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.
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        ProcedureReturn
    EndIf

    If success <> 1
        Debug "Expected a well-formed XML response."
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        ProcedureReturn
    EndIf

    If CkXml::ckTag(xml) <> "StartInstancesResponse"
        Debug "Unexpected EC2 response element."
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        ProcedureReturn
    EndIf

    If dryRun = 1
        Debug "Unexpected HTTP 200 for a dry run; do not treat this as authorization to proceed."
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        ProcedureReturn
    EndIf

    If (CkXml::ckHasChildWithTag(xml,"requestId") <> 1) OR (CkXml::ckGetChildContent(xml,"requestId") = "")
        Debug "Missing or empty requestId."
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        ProcedureReturn
    EndIf

    Debug "AWS request ID: " + CkXml::ckGetChildContent(xml,"requestId")
    If CkXml::ckNumChildrenAt(xml,"instancesSet") = 0
        Debug "Expected at least one instance state change."
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        ProcedureReturn
    EndIf

    i.i = 0
    While (i < CkXml::ckNumChildrenAt(xml,"instancesSet"))
        CkXml::setCkI(xml, i)
        If (CkXml::ckHasChildWithTag(xml,"instancesSet|item[i]|instanceId") <> 1) OR (CkXml::ckGetChildContent(xml,"instancesSet|item[i]|instanceId") = "")
            Debug "Missing or empty instancesSet|item[i]|instanceId."
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(endpoint)
            CkAuthAws::ckDispose(aws)
            CkRest::ckDispose(rest)
            CkSocket::ckDispose(connection)
            CkXml::ckDispose(xml)
            ProcedureReturn
        EndIf

        If (CkXml::ckHasChildWithTag(xml,"instancesSet|item[i]|previousState|name") <> 1) OR (CkXml::ckGetChildContent(xml,"instancesSet|item[i]|previousState|name") = "")
            Debug "Missing or empty instancesSet|item[i]|previousState|name."
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(endpoint)
            CkAuthAws::ckDispose(aws)
            CkRest::ckDispose(rest)
            CkSocket::ckDispose(connection)
            CkXml::ckDispose(xml)
            ProcedureReturn
        EndIf

        If (CkXml::ckHasChildWithTag(xml,"instancesSet|item[i]|currentState|name") <> 1) OR (CkXml::ckGetChildContent(xml,"instancesSet|item[i]|currentState|name") = "")
            Debug "Missing or empty instancesSet|item[i]|currentState|name."
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(endpoint)
            CkAuthAws::ckDispose(aws)
            CkRest::ckDispose(rest)
            CkSocket::ckDispose(connection)
            CkXml::ckDispose(xml)
            ProcedureReturn
        EndIf

        Debug "Instance: " + CkXml::ckGetChildContent(xml,"instancesSet|item[i]|instanceId")
        Debug "Previous state: " + CkXml::ckGetChildContent(xml,"instancesSet|item[i]|previousState|name")
        Debug "Current state: " + CkXml::ckGetChildContent(xml,"instancesSet|item[i]|currentState|name")
        i = i + 1
    Wend
    Debug "Request accepted; poll DescribeInstances to confirm the desired state."


    CkJsonObject::ckDispose(credentials)
    CkStringBuilder::ckDispose(endpoint)
    CkAuthAws::ckDispose(aws)
    CkRest::ckDispose(rest)
    CkSocket::ckDispose(connection)
    CkXml::ckDispose(xml)


    ProcedureReturn
EndProcedure