Amazon EC2: Check Instance Health and Scheduled Events
See more Amazon EC2 Examples
Read instance state, health summaries, and scheduled events across one account/region. Follow nextToken through every page, including an empty page with a token. A repeated token or the demonstration's 1000-page bound reports incomplete enumeration.
IncludeAllInstances includes non-running instances; it does not mean ignore explicit IDs. This example omits IDs and uses MaxResults=100. To select up to 100 explicit IDs, remove MaxResults and supply InstanceId.N. Keep following a returned token.
State and health are different. System health concerns AWS infrastructure; instance health concerns the guest; attached EBS health concerns volume reachability. Optional application/performance summaries are displayed when supplied. Missing fields are not interpreted as healthy. Scheduled events can require maintenance planning. Running and ok do not replace application readiness checks. Paginated results are not an atomic snapshot.
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:DescribeInstanceStatus. DescribeInstanceStatus requires 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.
AWS DescribeInstanceStatus reference
Chilkat DataFlex Downloads
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
Handle hoSeenTokens
String sNextToken
Boolean iMore
Integer iPage
String sResponseXml
String sErrorCode
Integer i
Integer j
String sTemp1
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
Get ComAddQueryParam Of hoRest "Action" "DescribeInstanceStatus" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not set Action."
Procedure_Return
End
// Include stopped and other non-running instances as well as running instances.
// This flag does NOT override InstanceId.N filters.
Get ComAddQueryParam Of hoRest "IncludeAllInstances" "true" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not set IncludeAllInstances."
Procedure_Return
End
Get ComAddQueryParam Of hoRest "MaxResults" "100" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not set MaxResults."
Procedure_Return
End
// To check up to 100 specific IDs instead: REMOVE MaxResults and add InstanceId.1, etc.
// AWS does not allow MaxResults together with explicit InstanceId.N parameters.
Get Create (RefClass(cComChilkatHashtable)) To hoSeenTokens
If (Not(IsComObjectCreated(hoSeenTokens))) Begin
Send CreateComObject of hoSeenTokens
End
Move "" To sNextToken
Move True To iMore
Move 0 To iPage
While (iMore = True)
If (iPage = 1000) Begin
Showln "Stopped at 1000 pages; status enumeration is incomplete."
// Save nextToken privately to resume. It is not a permanent checkpoint.
Procedure_Return
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."
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
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 <> "DescribeInstanceStatusResponse") Begin
Showln "Unexpected EC2 response element."
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 ComHasChildWithTag Of hoXml "instanceStatusSet" To bTemp1
If (bTemp1 <> True) Begin
Showln "Expected instanceStatusSet."
Procedure_Return
End
Move 0 To i
While (i < (ComNumChildrenAt(hoXml, "instanceStatusSet")))
Set ComI Of hoXml To i
Get ComHasChildWithTag Of hoXml "instanceStatusSet|item[i]|instanceId" To bTemp1
Get ComGetChildContent Of hoXml "instanceStatusSet|item[i]|instanceId" To sTemp1
If ((bTemp1 <> True) Or (sTemp1 = "")) Begin
Showln "Missing or empty instanceStatusSet|item[i]|instanceId."
Procedure_Return
End
Get ComGetChildContent Of hoXml "instanceStatusSet|item[i]|instanceId" To sTemp1
Showln "Instance: " sTemp1
// Read by element name; XML response element order is not guaranteed.
Get ComHasChildWithTag Of hoXml "instanceStatusSet|item[i]|availabilityZone" To bTemp1
If (bTemp1 = True) Begin
Get ComGetChildContent Of hoXml "instanceStatusSet|item[i]|availabilityZone" To sTemp1
Showln "Availability Zone: " sTemp1
End
Get ComHasChildWithTag Of hoXml "instanceStatusSet|item[i]|instanceState|name" To bTemp1
If (bTemp1 = True) Begin
Get ComGetChildContent Of hoXml "instanceStatusSet|item[i]|instanceState|name" To sTemp1
Showln "State: " sTemp1
End
Get ComHasChildWithTag Of hoXml "instanceStatusSet|item[i]|systemStatus|status" To bTemp1
If (bTemp1 = True) Begin
Get ComGetChildContent Of hoXml "instanceStatusSet|item[i]|systemStatus|status" To sTemp1
Showln "System health: " sTemp1
End
Get ComHasChildWithTag Of hoXml "instanceStatusSet|item[i]|instanceStatus|status" To bTemp1
If (bTemp1 = True) Begin
Get ComGetChildContent Of hoXml "instanceStatusSet|item[i]|instanceStatus|status" To sTemp1
Showln "Instance health: " sTemp1
End
Get ComHasChildWithTag Of hoXml "instanceStatusSet|item[i]|attachedEbsStatus|status" To bTemp1
If (bTemp1 = True) Begin
Get ComGetChildContent Of hoXml "instanceStatusSet|item[i]|attachedEbsStatus|status" To sTemp1
Showln "Attached EBS health: " sTemp1
End
Get ComHasChildWithTag Of hoXml "instanceStatusSet|item[i]|applicationStatus|status" To bTemp1
If (bTemp1 = True) Begin
Get ComGetChildContent Of hoXml "instanceStatusSet|item[i]|applicationStatus|status" To sTemp1
Showln "Application health: " sTemp1
End
Get ComHasChildWithTag Of hoXml "instanceStatusSet|item[i]|performanceStatus|status" To bTemp1
If (bTemp1 = True) Begin
Get ComGetChildContent Of hoXml "instanceStatusSet|item[i]|performanceStatus|status" To sTemp1
Showln "Performance health: " sTemp1
End
// Scheduled events may be absent. Event IDs and timestamps remain strings.
Move 0 To j
While (j < (ComNumChildrenAt(hoXml, "instanceStatusSet|item[i]|eventsSet")))
Set ComJ Of hoXml To j
Get ComHasChildWithTag Of hoXml "instanceStatusSet|item[i]|eventsSet|item[j]|instanceEventId" To bTemp1
If (bTemp1 = True) Begin
Get ComGetChildContent Of hoXml "instanceStatusSet|item[i]|eventsSet|item[j]|instanceEventId" To sTemp1
Showln "Event ID: " sTemp1
End
Get ComHasChildWithTag Of hoXml "instanceStatusSet|item[i]|eventsSet|item[j]|code" To bTemp1
If (bTemp1 = True) Begin
Get ComGetChildContent Of hoXml "instanceStatusSet|item[i]|eventsSet|item[j]|code" To sTemp1
Showln "Event: " sTemp1
End
Get ComHasChildWithTag Of hoXml "instanceStatusSet|item[i]|eventsSet|item[j]|description" To bTemp1
If (bTemp1 = True) Begin
Get ComGetChildContent Of hoXml "instanceStatusSet|item[i]|eventsSet|item[j]|description" To sTemp1
Showln "Description: " sTemp1
End
Get ComHasChildWithTag Of hoXml "instanceStatusSet|item[i]|eventsSet|item[j]|notBefore" To bTemp1
If (bTemp1 = True) Begin
Get ComGetChildContent Of hoXml "instanceStatusSet|item[i]|eventsSet|item[j]|notBefore" To sTemp1
Showln "Not before: " sTemp1
End
Get ComHasChildWithTag Of hoXml "instanceStatusSet|item[i]|eventsSet|item[j]|notAfter" To bTemp1
If (bTemp1 = True) Begin
Get ComGetChildContent Of hoXml "instanceStatusSet|item[i]|eventsSet|item[j]|notAfter" To sTemp1
Showln "Not after: " sTemp1
End
Get ComHasChildWithTag Of hoXml "instanceStatusSet|item[i]|eventsSet|item[j]|notBeforeDeadline" To bTemp1
If (bTemp1 = True) Begin
Get ComGetChildContent Of hoXml "instanceStatusSet|item[i]|eventsSet|item[j]|notBeforeDeadline" To sTemp1
Showln "Rescheduling deadline: " sTemp1
End
Move (j + 1) To j
Loop
Move (i + 1) To i
Loop
Move (iPage + 1) To iPage
Move False To iMore
Move "" To sNextToken
Get ComHasChildWithTag Of hoXml "nextToken" To bTemp1
If (bTemp1 = True) Begin
Get ComGetChildContent Of hoXml "nextToken" To sNextToken
End
If (sNextToken <> "") Begin
Get ComContains Of hoSeenTokens sNextToken To bTemp1
If (bTemp1 = True) Begin
Showln "Repeated pagination token; status enumeration is incomplete."
Procedure_Return
End
Get ComAddInt Of hoSeenTokens sNextToken 1 To iSuccess
If (iSuccess <> True) Begin
Showln "Could not track pagination."
Procedure_Return
End
// Replace the prior token; do not accumulate duplicate NextToken parameters.
If (iPage > 1) Begin
Get ComRemoveQueryParam Of hoRest "NextToken" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not remove the previous pagination token."
Procedure_Return
End
End
Get ComAddQueryParam Of hoRest "NextToken" sNextToken To iSuccess
If (iSuccess <> True) Begin
Showln "Could not set NextToken."
Procedure_Return
End
Move True To iMore
End
Loop
Showln "Status enumeration complete."
// A missing health field is unknown, not healthy. Even reported ok is not a
// substitute for the application's own readiness check.
End_Procedure