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 PHP ActiveX Downloads
<?php
// Assumes Chilkat is unlocked. See Global Unlock Sample.
$success = 0;
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the EC2 operation.
$credentials = new COM("Chilkat.JsonObject");
$credentials->Strict = 1;
$success = $credentials->LoadFile('qa_data/aws/ec2.json');
if ($success != 1) {
print 'Could not load private AWS credentials.' . "\n";
exit;
}
if (($credentials->JsonTypeOf('access_key') != 1) or ($credentials->stringOf('access_key') == '')) {
print 'Missing or invalid access_key.' . "\n";
exit;
}
if (($credentials->JsonTypeOf('secret_key') != 1) or ($credentials->stringOf('secret_key') == '')) {
print 'Missing or invalid secret_key.' . "\n";
exit;
}
// Set this once to the region containing the instances.
$region = 'us-west-2';
$endpoint = new COM("Chilkat.StringBuilder");
$endpoint->Append('ec2.');
$endpoint->Append($region);
$endpoint->Append('.amazonaws.com');
$aws = new COM("Chilkat.AuthAws");
$aws->AccessKey = $credentials->stringOf('access_key');
$aws->SecretKey = $credentials->stringOf('secret_key');
$aws->Region = $region;
$aws->ServiceName = 'ec2';
$aws->SignatureVersion = 4;
$rest = new COM("Chilkat.Rest");
$rest->ConnectTimeoutMs = 20000;
$rest->IdleTimeoutMs = 60000;
$success = $rest->SetAuthAws($aws);
if ($success != 1) {
print 'Could not configure AWS signing.' . "\n";
exit;
}
// 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') == 1) {
if ($credentials->JsonTypeOf('session_token') != 1) {
print 'session_token must be a string.' . "\n";
exit;
}
if ($credentials->stringOf('session_token') != '') {
$success = $rest->AddQueryParam('X-Amz-Security-Token',$credentials->stringOf('session_token'));
if ($success != 1) {
print 'Could not set the session-token parameter.' . "\n";
exit;
}
}
}
// Supply a Socket to explicitly enable TLS certificate verification.
$connection = new COM("Chilkat.Socket");
$connection->RequireSslCertVerify = 1;
$connection->MaxReadIdleMs = 60000;
$connection->MaxSendIdleMs = 60000;
$success = $connection->Connect($endpoint->getAsString(),443,1,20000);
if ($success != 1) {
print 'TLS connection failed; inspect diagnostics privately.' . "\n";
exit;
}
$success = $rest->UseConnection($connection,1);
if ($success != 1) {
print 'Could not attach the TLS connection.' . "\n";
exit;
}
// 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 = new COM("Chilkat.Xml");
$xml->Strict = 1;
$success = $rest->AddQueryParam('Version','2016-11-15');
if ($success != 1) {
print 'Could not set Version.' . "\n";
exit;
}
$success = $rest->AddQueryParam('Action','DescribeInstanceStatus');
if ($success != 1) {
print 'Could not set Action.' . "\n";
exit;
}
// Include stopped and other non-running instances as well as running instances.
// This flag does NOT override InstanceId.N filters.
$success = $rest->AddQueryParam('IncludeAllInstances','true');
if ($success != 1) {
print 'Could not set IncludeAllInstances.' . "\n";
exit;
}
$success = $rest->AddQueryParam('MaxResults','100');
if ($success != 1) {
print 'Could not set MaxResults.' . "\n";
exit;
}
// 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.
$seenTokens = new COM("Chilkat.Hashtable");
$nextToken = '';
$more = 1;
$page = 0;
while (($more == 1)) {
if ($page == 1000) {
print 'Stopped at 1000 pages; status enumeration is incomplete.' . "\n";
// Save nextToken privately to resume. It is not a permanent checkpoint.
exit;
}
$responseXml = $rest->fullRequestNoBody('GET','/');
if ($rest->LastMethodSuccess != 1) {
print 'Request did not complete; inspect diagnostics privately.' . "\n";
exit;
}
$success = $xml->LoadXml($responseXml);
if ($rest->ResponseStatusCode != 200) {
print 'EC2 HTTP status: ' . $rest->ResponseStatusCode . "\n";
if ($success == 1) {
if ($xml->HasChildWithTag('Errors|Error|Code') == 1) {
$errorCode = $xml->getChildContent('Errors|Error|Code');
print 'AWS error code: ' . $errorCode . "\n";
}
if ($xml->HasChildWithTag('RequestID') == 1) {
print 'AWS request ID: ' . $xml->getChildContent('RequestID') . "\n";
}
}
// 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.
exit;
}
if ($success != 1) {
print 'Expected a well-formed XML response.' . "\n";
exit;
}
if ($xml->Tag != 'DescribeInstanceStatusResponse') {
print 'Unexpected EC2 response element.' . "\n";
exit;
}
if (($xml->HasChildWithTag('requestId') != 1) or ($xml->getChildContent('requestId') == '')) {
print 'Missing or empty requestId.' . "\n";
exit;
}
print 'AWS request ID: ' . $xml->getChildContent('requestId') . "\n";
if ($xml->HasChildWithTag('instanceStatusSet') != 1) {
print 'Expected instanceStatusSet.' . "\n";
exit;
}
$i = 0;
while (($i < $xml->NumChildrenAt('instanceStatusSet'))) {
$xml->I = $i;
if (($xml->HasChildWithTag('instanceStatusSet|item[i]|instanceId') != 1) or ($xml->getChildContent('instanceStatusSet|item[i]|instanceId') == '')) {
print 'Missing or empty instanceStatusSet|item[i]|instanceId.' . "\n";
exit;
}
print 'Instance: ' . $xml->getChildContent('instanceStatusSet|item[i]|instanceId') . "\n";
// Read by element name; XML response element order is not guaranteed.
if ($xml->HasChildWithTag('instanceStatusSet|item[i]|availabilityZone') == 1) {
print 'Availability Zone: ' . $xml->getChildContent('instanceStatusSet|item[i]|availabilityZone') . "\n";
}
if ($xml->HasChildWithTag('instanceStatusSet|item[i]|instanceState|name') == 1) {
print 'State: ' . $xml->getChildContent('instanceStatusSet|item[i]|instanceState|name') . "\n";
}
if ($xml->HasChildWithTag('instanceStatusSet|item[i]|systemStatus|status') == 1) {
print 'System health: ' . $xml->getChildContent('instanceStatusSet|item[i]|systemStatus|status') . "\n";
}
if ($xml->HasChildWithTag('instanceStatusSet|item[i]|instanceStatus|status') == 1) {
print 'Instance health: ' . $xml->getChildContent('instanceStatusSet|item[i]|instanceStatus|status') . "\n";
}
if ($xml->HasChildWithTag('instanceStatusSet|item[i]|attachedEbsStatus|status') == 1) {
print 'Attached EBS health: ' . $xml->getChildContent('instanceStatusSet|item[i]|attachedEbsStatus|status') . "\n";
}
if ($xml->HasChildWithTag('instanceStatusSet|item[i]|applicationStatus|status') == 1) {
print 'Application health: ' . $xml->getChildContent('instanceStatusSet|item[i]|applicationStatus|status') . "\n";
}
if ($xml->HasChildWithTag('instanceStatusSet|item[i]|performanceStatus|status') == 1) {
print 'Performance health: ' . $xml->getChildContent('instanceStatusSet|item[i]|performanceStatus|status') . "\n";
}
// Scheduled events may be absent. Event IDs and timestamps remain strings.
$j = 0;
while (($j < $xml->NumChildrenAt('instanceStatusSet|item[i]|eventsSet'))) {
$xml->J = $j;
if ($xml->HasChildWithTag('instanceStatusSet|item[i]|eventsSet|item[j]|instanceEventId') == 1) {
print 'Event ID: ' . $xml->getChildContent('instanceStatusSet|item[i]|eventsSet|item[j]|instanceEventId') . "\n";
}
if ($xml->HasChildWithTag('instanceStatusSet|item[i]|eventsSet|item[j]|code') == 1) {
print 'Event: ' . $xml->getChildContent('instanceStatusSet|item[i]|eventsSet|item[j]|code') . "\n";
}
if ($xml->HasChildWithTag('instanceStatusSet|item[i]|eventsSet|item[j]|description') == 1) {
print 'Description: ' . $xml->getChildContent('instanceStatusSet|item[i]|eventsSet|item[j]|description') . "\n";
}
if ($xml->HasChildWithTag('instanceStatusSet|item[i]|eventsSet|item[j]|notBefore') == 1) {
print 'Not before: ' . $xml->getChildContent('instanceStatusSet|item[i]|eventsSet|item[j]|notBefore') . "\n";
}
if ($xml->HasChildWithTag('instanceStatusSet|item[i]|eventsSet|item[j]|notAfter') == 1) {
print 'Not after: ' . $xml->getChildContent('instanceStatusSet|item[i]|eventsSet|item[j]|notAfter') . "\n";
}
if ($xml->HasChildWithTag('instanceStatusSet|item[i]|eventsSet|item[j]|notBeforeDeadline') == 1) {
print 'Rescheduling deadline: ' . $xml->getChildContent('instanceStatusSet|item[i]|eventsSet|item[j]|notBeforeDeadline') . "\n";
}
$j = $j + 1;
}
$i = $i + 1;
}
$page = $page + 1;
$more = 0;
$nextToken = '';
if ($xml->HasChildWithTag('nextToken') == 1) {
$nextToken = $xml->getChildContent('nextToken');
}
if ($nextToken != '') {
if ($seenTokens->Contains($nextToken) == 1) {
print 'Repeated pagination token; status enumeration is incomplete.' . "\n";
exit;
}
$success = $seenTokens->AddInt($nextToken,1);
if ($success != 1) {
print 'Could not track pagination.' . "\n";
exit;
}
// Replace the prior token; do not accumulate duplicate NextToken parameters.
if ($page > 1) {
$success = $rest->RemoveQueryParam('NextToken');
if ($success != 1) {
print 'Could not remove the previous pagination token.' . "\n";
exit;
}
}
$success = $rest->AddQueryParam('NextToken',$nextToken);
if ($success != 1) {
print 'Could not set NextToken.' . "\n";
exit;
}
$more = 1;
}
}
print 'Status enumeration complete.' . "\n";
// A missing health field is unknown, not healthy. Even reported ok is not a
// substitute for the application's own readiness check.
?>