Amazon EC2: Wait for Instance State and Health Checks
See more Amazon EC2 Examples
Poll one instance until it is running with both system and instance health explicitly ok, or change desiredState to stopped for a state-only wait. Missing status entries and missing health fields are not success. A terminating state stops the wait. Application readiness needs its own probe; the two EC2 checks do not test your application.
Uses at most 60 reads with exponential delays capped at 10 seconds. HTTP timeouts add to elapsed time. Bounded retries cover throttling, selected service errors, and temporary InvalidInstanceID.NotFound after a recent launch; persistent absence can mean a wrong ID, account, or region. Authentication/permission failures stop immediately. The example makes no state-changing 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:DescribeInstanceStatus. 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.
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;
}
$responseXml = '';
$errorCode = '';
$instanceId = 'i-1234567890abcdef0';
// Supported goals: "running" (with health checks) or "stopped" (state only).
$desiredState = 'running';
if (($desiredState != 'running') and ($desiredState != 'stopped')) {
print 'Choose running or stopped.' . "\n";
exit;
}
$success = $rest->AddQueryParam('Action','DescribeInstanceStatus');
if ($success != 1) {
print 'Could not set Action.' . "\n";
exit;
}
$success = $rest->AddQueryParam('InstanceId.1',$instanceId);
if ($success != 1) {
print 'Could not set InstanceId.1.' . "\n";
exit;
}
$success = $rest->AddQueryParam('IncludeAllInstances','true');
if ($success != 1) {
print 'Could not set IncludeAllInstances.' . "\n";
exit;
}
// No MaxResults with explicit IDs. A missing entry is not readiness.
$state = '';
// At most 60 attempts, with delays growing from 2 to 10 seconds.
// HTTP timeouts add to total elapsed time. No busy loop or automatic write retry.
$attempt = 0;
$delayMs = 2000;
$retryRead = 0;
while (($attempt < 60)) {
$retryRead = 0;
$responseXml = $rest->fullRequestNoBody('GET','/');
if ($rest->LastMethodSuccess != 1) {
print 'Polling transport failed; resume the read later. No write was retried.' . "\n";
exit;
}
$success = $xml->LoadXml($responseXml);
if ($rest->ResponseStatusCode != 200) {
$errorCode = '';
if ($success == 1) {
if ($xml->HasChildWithTag('Errors|Error|Code') == 1) {
$errorCode = $xml->getChildContent('Errors|Error|Code');
}
}
if (($errorCode == 'RequestLimitExceeded') or ($errorCode == 'InternalError') or ($errorCode == 'ServiceUnavailable') or ($errorCode == 'InvalidInstanceID.NotFound')) {
$retryRead = 1;
}
else {
print 'Polling failed: HTTP ' . $rest->ResponseStatusCode . '; AWS code: ' . $errorCode . "\n";
exit;
}
}
if ($retryRead == 0) {
if ($success != 1) {
print 'Expected a well-formed XML response.' . "\n";
exit;
}
if ($xml->Tag != 'DescribeInstanceStatusResponse') {
print 'Unexpected polling response.' . "\n";
exit;
}
if (($xml->HasChildWithTag('requestId') != 1) or ($xml->getChildContent('requestId') == '')) {
print 'Missing or empty requestId.' . "\n";
exit;
}
if ($xml->HasChildWithTag('instanceStatusSet') != 1) {
print 'Expected instanceStatusSet.' . "\n";
exit;
}
if ($xml->NumChildrenAt('instanceStatusSet') > 0) {
if ($xml->NumChildrenAt('instanceStatusSet') != 1) {
print 'Expected one instance status.' . "\n";
exit;
}
if (($xml->HasChildWithTag('instanceStatusSet|item|instanceId') != 1) or ($xml->getChildContent('instanceStatusSet|item|instanceId') == '')) {
print 'Missing or empty instanceStatusSet|item|instanceId.' . "\n";
exit;
}
if ($xml->getChildContent('instanceStatusSet|item|instanceId') != $instanceId) {
print 'Unexpected instance ID.' . "\n";
exit;
}
if (($xml->HasChildWithTag('instanceStatusSet|item|instanceState|name') != 1) or ($xml->getChildContent('instanceStatusSet|item|instanceState|name') == '')) {
print 'Missing or empty instanceStatusSet|item|instanceState|name.' . "\n";
exit;
}
$state = $xml->getChildContent('instanceStatusSet|item|instanceState|name');
print 'Observed state: ' . $state . "\n";
if (($state == 'shutting-down') or ($state == 'terminated')) {
print 'Instance is terminating or terminated; requested readiness cannot be reached.' . "\n";
exit;
}
if ($state == $desiredState) {
if ($desiredState == 'stopped') {
print 'Instance reached stopped state.' . "\n";
exit;
}
// Both statuses must explicitly be ok. Missing/initializing/impaired is not ready.
if (($xml->getChildContent('instanceStatusSet|item|systemStatus|status') == 'ok') and ($xml->getChildContent('instanceStatusSet|item|instanceStatus|status') == 'ok')) {
print 'Instance is running and both EC2 health checks are ok.' . "\n";
print 'Check application readiness separately.' . "\n";
exit;
}
}
}
}
$attempt = $attempt + 1;
if ($attempt < 60) {
$connection->SleepMs($delayMs);
if ($delayMs < 10000) {
$delayMs = $delayMs * 2;
if ($delayMs > 10000) {
$delayMs = 10000;
}
}
}
}
print 'Polling limit reached; completion has not been confirmed. Resume checking later.' . "\n";
?>