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.
Chilkat Xojo Plugin Downloads
// 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
// Keep IDs as strings. Choose an instance in the configured account and region.
Dim instanceId As String
instanceId = "i-1234567890abcdef0"
// Change to false only when ready for the live operation described above.
Dim dryRun As Boolean
dryRun = True
success = rest.AddQueryParam("Action","StartInstances")
If (success <> True) Then
System.DebugLog("Could not set Action.")
Return
End If
success = rest.AddQueryParam("InstanceId.1",instanceId)
If (success <> True) Then
System.DebugLog("Could not set InstanceId.1.")
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
Dim responseXml As String
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.
// Do not blindly repeat a reboot after a timeout.
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
Dim errorCode As String
errorCode = xml.GetChildContent("Errors|Error|Code")
If ((dryRun = True) And (errorCode = "DryRunOperation")) Then
System.DebugLog("Dry run authorized. No instance 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 <> "StartInstancesResponse") 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") = 0) Then
System.DebugLog("Expected at least one instance state change.")
Return
End If
Dim i As Int32
i = 0
While (i < xml.NumChildrenAt("instancesSet"))
xml.I = i
If ((xml.HasChildWithTag("instancesSet|item[i]|instanceId") <> True) Or (xml.GetChildContent("instancesSet|item[i]|instanceId") = "")) Then
System.DebugLog("Missing or empty instancesSet|item[i]|instanceId.")
Return
End If
If ((xml.HasChildWithTag("instancesSet|item[i]|previousState|name") <> True) Or (xml.GetChildContent("instancesSet|item[i]|previousState|name") = "")) Then
System.DebugLog("Missing or empty instancesSet|item[i]|previousState|name.")
Return
End If
If ((xml.HasChildWithTag("instancesSet|item[i]|currentState|name") <> True) Or (xml.GetChildContent("instancesSet|item[i]|currentState|name") = "")) Then
System.DebugLog("Missing or empty instancesSet|item[i]|currentState|name.")
Return
End If
System.DebugLog("Instance: " + xml.GetChildContent("instancesSet|item[i]|instanceId"))
System.DebugLog("Previous state: " + xml.GetChildContent("instancesSet|item[i]|previousState|name"))
System.DebugLog("Current state: " + xml.GetChildContent("instancesSet|item[i]|currentState|name"))
i = i + 1
Wend
System.DebugLog("Request accepted; poll DescribeInstances to confirm the desired state.")