Amazon EC2: Find Instances by Tag and State
See more Amazon EC2 Examples
Find running instances whose Name tag matches the supplied value. Parses the two-level reservationSet/instancesSet structure, IDs, addresses, and tags. Different filters are combined with AND; multiple values within one filter are alternatives. Names can match multiple instances. Missing public-address fields are normal for private instances.
Follows nextToken even after an empty page. Tokens are opaque strings; replace the previous NextToken rather than adding duplicates. A repeated token or the 1000-page demonstration bound reports incomplete results. Pages are not an atomic snapshot, and response order is not guaranteed.
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:DescribeInstances. 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.
Chilkat Objective-C Downloads
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoStringBuilder.h>
#import <CkoAuthAws.h>
#import <CkoRest.h>
#import <CkoSocket.h>
#import <CkoXml.h>
#import <CkoHashtable.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 *instanceName = @"example-instance";
int i = 0;
int j = 0;
int k = 0;
success = [rest AddQueryParam: @"Action" value: @"DescribeInstances"];
if (success != YES) {
NSLog(@"%@",@"Could not set Action.");
return;
}
success = [rest AddQueryParam: @"Filter.1.Name" value: @"tag:Name"];
if (success != YES) {
NSLog(@"%@",@"Could not set Filter.1.Name.");
return;
}
success = [rest AddQueryParam: @"Filter.1.Value.1" value: instanceName];
if (success != YES) {
NSLog(@"%@",@"Could not set Filter.1.Value.1.");
return;
}
success = [rest AddQueryParam: @"Filter.2.Name" value: @"instance-state-name"];
if (success != YES) {
NSLog(@"%@",@"Could not set Filter.2.Name.");
return;
}
success = [rest AddQueryParam: @"Filter.2.Value.1" value: @"running"];
if (success != YES) {
NSLog(@"%@",@"Could not set Filter.2.Value.1.");
return;
}
// Filters are ANDed. Remove a filter deliberately to broaden the search.
// Name tags are not unique: process every returned instance, not just the first.
success = [rest AddQueryParam: @"MaxResults" value: @"100"];
if (success != YES) {
NSLog(@"%@",@"Could not set MaxResults.");
return;
}
CkoHashtable *seenTokens = [[CkoHashtable alloc] init];
NSString *nextToken = @"";
BOOL more = YES;
int page = 0;
while ((more == YES)) {
if (page == 1000) {
NSLog(@"%@",@"Page limit reached; enumeration is incomplete. Retain nextToken privately to resume.");
return;
}
responseXml = [rest FullRequestNoBody: @"GET" uriPath: @"/"];
if (rest.LastMethodSuccess != YES) {
NSLog(@"%@",@"Request did not complete; inspect diagnostics privately.");
return;
}
success = [xml LoadXml: responseXml];
if ([rest.ResponseStatusCode intValue] != 200) {
NSLog(@"%@%d",@"EC2 HTTP status: ",[rest.ResponseStatusCode intValue]);
if (success == YES) {
if ([xml HasChildWithTag: @"Errors|Error|Code"] == YES) {
errorCode = [xml GetChildContent: @"Errors|Error|Code"];
NSLog(@"%@%@",@"AWS error code: ",errorCode);
}
if ([xml HasChildWithTag: @"RequestID"] == YES) {
NSLog(@"%@%@",@"AWS request ID: ",[xml GetChildContent: @"RequestID"]);
}
}
// 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;
}
if (success != YES) {
NSLog(@"%@",@"Expected a well-formed XML response.");
return;
}
if (xml.Tag != @"DescribeInstancesResponse") {
NSLog(@"%@",@"Unexpected EC2 response element.");
return;
}
if (([xml HasChildWithTag: @"requestId"] != YES) || ([xml GetChildContent: @"requestId"] == @"")) {
NSLog(@"%@",@"Missing or empty requestId.");
return;
}
NSLog(@"%@%@",@"AWS request ID: ",[xml GetChildContent: @"requestId"]);
if ([xml HasChildWithTag: @"reservationSet"] != YES) {
NSLog(@"%@",@"Expected reservationSet.");
return;
}
i = 0;
while ((i < [[xml NumChildrenAt: @"reservationSet"] intValue])) {
xml.I = [NSNumber numberWithInt: i];
j = 0;
while ((j < [[xml NumChildrenAt: @"reservationSet|item[i]|instancesSet"] intValue])) {
xml.J = [NSNumber numberWithInt: j];
if (([xml HasChildWithTag: @"reservationSet|item[i]|instancesSet|item[j]|instanceId"] != YES) || ([xml GetChildContent: @"reservationSet|item[i]|instancesSet|item[j]|instanceId"] == @"")) {
NSLog(@"%@",@"Missing or empty reservationSet|item[i]|instancesSet|item[j]|instanceId.");
return;
}
NSLog(@"%@%@",@"Instance ID: ",[xml GetChildContent: @"reservationSet|item[i]|instancesSet|item[j]|instanceId"]);
if ([xml HasChildWithTag: @"reservationSet|item[i]|instancesSet|item[j]|instanceState|name"] == YES) {
NSLog(@"%@%@",@"State: ",[xml GetChildContent: @"reservationSet|item[i]|instancesSet|item[j]|instanceState|name"]);
}
if ([xml HasChildWithTag: @"reservationSet|item[i]|instancesSet|item[j]|instanceType"] == YES) {
NSLog(@"%@%@",@"Type: ",[xml GetChildContent: @"reservationSet|item[i]|instancesSet|item[j]|instanceType"]);
}
if ([xml HasChildWithTag: @"reservationSet|item[i]|instancesSet|item[j]|imageId"] == YES) {
NSLog(@"%@%@",@"AMI: ",[xml GetChildContent: @"reservationSet|item[i]|instancesSet|item[j]|imageId"]);
}
if ([xml HasChildWithTag: @"reservationSet|item[i]|instancesSet|item[j]|privateIpAddress"] == YES) {
NSLog(@"%@%@",@"Private IPv4: ",[xml GetChildContent: @"reservationSet|item[i]|instancesSet|item[j]|privateIpAddress"]);
}
if ([xml HasChildWithTag: @"reservationSet|item[i]|instancesSet|item[j]|ipAddress"] == YES) {
NSLog(@"%@%@",@"Public IPv4: ",[xml GetChildContent: @"reservationSet|item[i]|instancesSet|item[j]|ipAddress"]);
}
if ([xml HasChildWithTag: @"reservationSet|item[i]|instancesSet|item[j]|privateDnsName"] == YES) {
NSLog(@"%@%@",@"Private DNS: ",[xml GetChildContent: @"reservationSet|item[i]|instancesSet|item[j]|privateDnsName"]);
}
if ([xml HasChildWithTag: @"reservationSet|item[i]|instancesSet|item[j]|dnsName"] == YES) {
NSLog(@"%@%@",@"Public DNS: ",[xml GetChildContent: @"reservationSet|item[i]|instancesSet|item[j]|dnsName"]);
}
if ([xml HasChildWithTag: @"reservationSet|item[i]|instancesSet|item[j]|subnetId"] == YES) {
NSLog(@"%@%@",@"Subnet: ",[xml GetChildContent: @"reservationSet|item[i]|instancesSet|item[j]|subnetId"]);
}
if ([xml HasChildWithTag: @"reservationSet|item[i]|instancesSet|item[j]|vpcId"] == YES) {
NSLog(@"%@%@",@"VPC: ",[xml GetChildContent: @"reservationSet|item[i]|instancesSet|item[j]|vpcId"]);
}
k = 0;
while ((k < [[xml NumChildrenAt: @"reservationSet|item[i]|instancesSet|item[j]|tagSet"] intValue])) {
xml.K = [NSNumber numberWithInt: k];
if (([xml HasChildWithTag: @"reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key"] != YES) || ([xml GetChildContent: @"reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key"] == @"")) {
NSLog(@"%@",@"Missing or empty reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key.");
return;
}
NSLog(@"%@%@",@"Tag key: ",[xml GetChildContent: @"reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|key"]);
if ([xml HasChildWithTag: @"reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|value"] == YES) {
NSLog(@"%@%@",@"Tag value: ",[xml GetChildContent: @"reservationSet|item[i]|instancesSet|item[j]|tagSet|item[k]|value"]);
}
k = k + 1;
}
j = j + 1;
}
i = i + 1;
}
page = page + 1;
more = NO;
nextToken = @"";
if ([xml HasChildWithTag: @"nextToken"] == YES) {
nextToken = [xml GetChildContent: @"nextToken"];
}
if (nextToken != @"") {
if ([seenTokens Contains: nextToken] == YES) {
NSLog(@"%@",@"Repeated pagination token; enumeration is incomplete.");
return;
}
success = [seenTokens AddInt: nextToken value: [NSNumber numberWithInt: 1]];
if (success != YES) {
NSLog(@"%@",@"Could not track pages.");
return;
}
if (page > 1) {
success = [rest RemoveQueryParam: @"NextToken"];
if (success != YES) {
NSLog(@"%@",@"Could not replace pagination token.");
return;
}
}
success = [rest AddQueryParam: @"NextToken" value: nextToken];
if (success != YES) {
NSLog(@"%@",@"Could not set NextToken.");
return;
}
more = YES;
}
}
NSLog(@"%@",@"Enumeration complete.");