Sample code for 30+ languages & platforms
Objective-C Requires Chilkat v11.6.0+

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 Objective-C Downloads

Objective-C
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoStringBuilder.h>
#import <CkoAuthAws.h>
#import <CkoRest.h>
#import <CkoSocket.h>
#import <CkoXml.h>

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
BOOL success = NO;
//  Private configuration, not a file in public web content or source control.
//  Load current IAM credentials authorized for the EC2 operation.
CkoJsonObject *credentials = [[CkoJsonObject alloc] init];
credentials.Strict = YES;
success = [credentials LoadFile: @"qa_data/aws/ec2.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not load private AWS credentials.");
    return;
}

if (([[credentials JsonTypeOf: @"access_key"] intValue] != 1) || ([credentials StringOf: @"access_key"] == @"")) {
    NSLog(@"%@",@"Missing or invalid access_key.");
    return;
}

if (([[credentials JsonTypeOf: @"secret_key"] intValue] != 1) || ([credentials StringOf: @"secret_key"] == @"")) {
    NSLog(@"%@",@"Missing or invalid secret_key.");
    return;
}

//  Set this once to the region containing the instances.
NSString *region = @"us-west-2";
CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
[endpoint Append: @"ec2."];
[endpoint Append: region];
[endpoint Append: @".amazonaws.com"];
CkoAuthAws *aws = [[CkoAuthAws alloc] init];
aws.AccessKey = [credentials StringOf: @"access_key"];
aws.SecretKey = [credentials StringOf: @"secret_key"];
aws.Region = region;
aws.ServiceName = @"ec2";
aws.SignatureVersion = [NSNumber numberWithInt:4];
CkoRest *rest = [[CkoRest alloc] init];
rest.ConnectTimeoutMs = [NSNumber numberWithInt:20000];
rest.IdleTimeoutMs = [NSNumber numberWithInt:60000];
success = [rest SetAuthAws: aws];
if (success != YES) {
    NSLog(@"%@",@"Could not configure AWS signing.");
    return;
}

//  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"] == YES) {
    if ([[credentials JsonTypeOf: @"session_token"] intValue] != 1) {
        NSLog(@"%@",@"session_token must be a string.");
        return;
    }

    if ([credentials StringOf: @"session_token"] != @"") {
        success = [rest AddQueryParam: @"X-Amz-Security-Token" value: [credentials StringOf: @"session_token"]];
        if (success != YES) {
            NSLog(@"%@",@"Could not set the session-token parameter.");
            return;
        }

    }

}

//  Supply a Socket to explicitly enable TLS certificate verification.
CkoSocket *connection = [[CkoSocket alloc] init];
connection.RequireSslCertVerify = YES;
connection.MaxReadIdleMs = [NSNumber numberWithInt:60000];
connection.MaxSendIdleMs = [NSNumber numberWithInt:60000];
success = [connection Connect: [endpoint GetAsString] port: [NSNumber numberWithInt: 443] ssl: YES maxWaitMs: [NSNumber numberWithInt: 20000]];
if (success != YES) {
    NSLog(@"%@",@"TLS connection failed; inspect diagnostics privately.");
    return;
}

success = [rest UseConnection: connection autoReconnect: YES];
if (success != YES) {
    NSLog(@"%@",@"Could not attach the TLS connection.");
    return;
}

//  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.
CkoXml *xml = [[CkoXml alloc] init];
xml.Strict = YES;
success = [rest AddQueryParam: @"Version" value: @"2016-11-15"];
if (success != YES) {
    NSLog(@"%@",@"Could not set Version.");
    return;
}

NSString *responseXml = @"";
NSString *errorCode = @"";
NSString *instanceId = @"i-1234567890abcdef0";
//  Supported goals: "running" (with health checks) or "stopped" (state only).
NSString *desiredState = @"running";
if ((desiredState != @"running") && (desiredState != @"stopped")) {
    NSLog(@"%@",@"Choose running or stopped.");
    return;
}

success = [rest AddQueryParam: @"Action" value: @"DescribeInstanceStatus"];
if (success != YES) {
    NSLog(@"%@",@"Could not set Action.");
    return;
}

success = [rest AddQueryParam: @"InstanceId.1" value: instanceId];
if (success != YES) {
    NSLog(@"%@",@"Could not set InstanceId.1.");
    return;
}

success = [rest AddQueryParam: @"IncludeAllInstances" value: @"true"];
if (success != YES) {
    NSLog(@"%@",@"Could not set IncludeAllInstances.");
    return;
}

//  No MaxResults with explicit IDs. A missing entry is not readiness.
NSString *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.
int attempt = 0;
int delayMs = 2000;
BOOL retryRead = NO;
while ((attempt < 60)) {
    retryRead = NO;
    responseXml = [rest FullRequestNoBody: @"GET" uriPath: @"/"];
    if (rest.LastMethodSuccess != YES) {
        NSLog(@"%@",@"Polling transport failed; resume the read later. No write was retried.");
        return;
    }

    success = [xml LoadXml: responseXml];
    if ([rest.ResponseStatusCode intValue] != 200) {
        errorCode = @"";
        if (success == YES) {
            if ([xml HasChildWithTag: @"Errors|Error|Code"] == YES) {
                errorCode = [xml GetChildContent: @"Errors|Error|Code"];
            }

        }

        if ((errorCode == @"RequestLimitExceeded") || (errorCode == @"InternalError") || (errorCode == @"ServiceUnavailable") || (errorCode == @"InvalidInstanceID.NotFound")) {
            retryRead = YES;
        }
        else {
            NSLog(@"%@%d%@%@",@"Polling failed: HTTP ",[rest.ResponseStatusCode intValue],@"; AWS code: ",errorCode);
            return;
        }

    }

    if (retryRead == NO) {
        if (success != YES) {
            NSLog(@"%@",@"Expected a well-formed XML response.");
            return;
        }

        if (xml.Tag != @"DescribeInstanceStatusResponse") {
            NSLog(@"%@",@"Unexpected polling response.");
            return;
        }

        if (([xml HasChildWithTag: @"requestId"] != YES) || ([xml GetChildContent: @"requestId"] == @"")) {
            NSLog(@"%@",@"Missing or empty requestId.");
            return;
        }

        if ([xml HasChildWithTag: @"instanceStatusSet"] != YES) {
            NSLog(@"%@",@"Expected instanceStatusSet.");
            return;
        }

        if ([[xml NumChildrenAt: @"instanceStatusSet"] intValue] > 0) {
            if ([[xml NumChildrenAt: @"instanceStatusSet"] intValue] != 1) {
                NSLog(@"%@",@"Expected one instance status.");
                return;
            }

            if (([xml HasChildWithTag: @"instanceStatusSet|item|instanceId"] != YES) || ([xml GetChildContent: @"instanceStatusSet|item|instanceId"] == @"")) {
                NSLog(@"%@",@"Missing or empty instanceStatusSet|item|instanceId.");
                return;
            }

            if ([xml GetChildContent: @"instanceStatusSet|item|instanceId"] != instanceId) {
                NSLog(@"%@",@"Unexpected instance ID.");
                return;
            }

            if (([xml HasChildWithTag: @"instanceStatusSet|item|instanceState|name"] != YES) || ([xml GetChildContent: @"instanceStatusSet|item|instanceState|name"] == @"")) {
                NSLog(@"%@",@"Missing or empty instanceStatusSet|item|instanceState|name.");
                return;
            }

            state = [xml GetChildContent: @"instanceStatusSet|item|instanceState|name"];
            NSLog(@"%@%@",@"Observed state: ",state);
            if ((state == @"shutting-down") || (state == @"terminated")) {
                NSLog(@"%@",@"Instance is terminating or terminated; requested readiness cannot be reached.");
                return;
            }

            if (state == desiredState) {
                if (desiredState == @"stopped") {
                    NSLog(@"%@",@"Instance reached stopped state.");
                    return;
                }

                //  Both statuses must explicitly be ok. Missing/initializing/impaired is not ready.
                if (([xml GetChildContent: @"instanceStatusSet|item|systemStatus|status"] == @"ok") && ([xml GetChildContent: @"instanceStatusSet|item|instanceStatus|status"] == @"ok")) {
                    NSLog(@"%@",@"Instance is running and both EC2 health checks are ok.");
                    NSLog(@"%@",@"Check application readiness separately.");
                    return;
                }

            }

        }

    }

    attempt = attempt + 1;
    if (attempt < 60) {
        [connection SleepMs: [NSNumber numberWithInt: delayMs]];
        if (delayMs < 10000) {
            delayMs = delayMs * 2;
            if (delayMs > 10000) {
                delayMs = 10000;
            }

        }

    }

}

NSLog(@"%@",@"Polling limit reached; completion has not been confirmed. Resume checking later.");