Sample code for 30+ languages & platforms
Delphi DLL Requires Chilkat v11.6.0+

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 Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
credentials: HCkJsonObject;
region: PWideChar;
endpoint: HCkStringBuilder;
aws: HCkAuthAws;
rest: HCkRest;
connection: HCkSocket;
xml: HCkXml;
seenTokens: HCkHashtable;
nextToken: PWideChar;
more: Boolean;
page: Integer;
responseXml: PWideChar;
errorCode: PWideChar;
i: Integer;
j: Integer;

begin
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
success := False;
//  Private configuration, not a file in public web content or source control.
//  Load current IAM credentials authorized for the EC2 operation.
credentials := CkJsonObject_Create();
CkJsonObject_putStrict(credentials,True);
success := CkJsonObject_LoadFile(credentials,'qa_data/aws/ec2.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load private AWS credentials.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(credentials,'access_key') <> 1) or (CkJsonObject__stringOf(credentials,'access_key') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid access_key.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(credentials,'secret_key') <> 1) or (CkJsonObject__stringOf(credentials,'secret_key') = '')) then
  begin
    Memo1.Lines.Add('Missing or invalid secret_key.');
    Exit;
  end;
//  Set this once to the region containing the instances.
region := 'us-west-2';
endpoint := CkStringBuilder_Create();
CkStringBuilder_Append(endpoint,'ec2.');
CkStringBuilder_Append(endpoint,region);
CkStringBuilder_Append(endpoint,'.amazonaws.com');
aws := CkAuthAws_Create();
CkAuthAws_putAccessKey(aws,CkJsonObject__stringOf(credentials,'access_key'));
CkAuthAws_putSecretKey(aws,CkJsonObject__stringOf(credentials,'secret_key'));
CkAuthAws_putRegion(aws,region);
CkAuthAws_putServiceName(aws,'ec2');
CkAuthAws_putSignatureVersion(aws,4);
rest := CkRest_Create();
CkRest_putConnectTimeoutMs(rest,20000);
CkRest_putIdleTimeoutMs(rest,60000);
success := CkRest_SetAuthAws(rest,aws);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not configure AWS signing.');
    Exit;
  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.
if (CkJsonObject_HasMember(credentials,'session_token') = True) then
  begin
    if (CkJsonObject_JsonTypeOf(credentials,'session_token') <> 1) then
      begin
        Memo1.Lines.Add('session_token must be a string.');
        Exit;
      end;
    if (CkJsonObject__stringOf(credentials,'session_token') <> '') then
      begin
        success := CkRest_AddQueryParam(rest,'X-Amz-Security-Token',CkJsonObject__stringOf(credentials,'session_token'));
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not set the session-token parameter.');
            Exit;
          end;
      end;
  end;
//  Supply a Socket to explicitly enable TLS certificate verification.
connection := CkSocket_Create();
CkSocket_putRequireSslCertVerify(connection,True);
CkSocket_putMaxReadIdleMs(connection,60000);
CkSocket_putMaxSendIdleMs(connection,60000);
success := CkSocket_Connect(connection,CkStringBuilder__getAsString(endpoint),443,True,20000);
if (success <> True) then
  begin
    Memo1.Lines.Add('TLS connection failed; inspect diagnostics privately.');
    Exit;
  end;
success := CkRest_UseConnection(rest,connection,True);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not attach the TLS connection.');
    Exit;
  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.
xml := CkXml_Create();
CkXml_putStrict(xml,True);
success := CkRest_AddQueryParam(rest,'Version','2016-11-15');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set Version.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'Action','DescribeInstanceStatus');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set Action.');
    Exit;
  end;
//  Include stopped and other non-running instances as well as running instances.
//  This flag does NOT override InstanceId.N filters.
success := CkRest_AddQueryParam(rest,'IncludeAllInstances','true');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set IncludeAllInstances.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'MaxResults','100');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set MaxResults.');
    Exit;
  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.
seenTokens := CkHashtable_Create();
nextToken := '';
more := True;
page := 0;
while (more = True) do
  begin
    if (page = 1000) then
      begin
        Memo1.Lines.Add('Stopped at 1000 pages; status enumeration is incomplete.');
        //  Save nextToken privately to resume. It is not a permanent checkpoint.
        Exit;
      end;
    responseXml := CkRest__fullRequestNoBody(rest,'GET','/');
    if (CkRest_getLastMethodSuccess(rest) <> True) then
      begin
        Memo1.Lines.Add('Request did not complete; inspect diagnostics privately.');
        Exit;
      end;
    success := CkXml_LoadXml(xml,responseXml);
    if (CkRest_getResponseStatusCode(rest) <> 200) then
      begin
        Memo1.Lines.Add('EC2 HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
        if (success = True) then
          begin
            if (CkXml_HasChildWithTag(xml,'Errors|Error|Code') = True) then
              begin
                errorCode := CkXml__getChildContent(xml,'Errors|Error|Code');
                Memo1.Lines.Add('AWS error code: ' + errorCode);
              end;
            if (CkXml_HasChildWithTag(xml,'RequestID') = True) then
              begin
                Memo1.Lines.Add('AWS request ID: ' + CkXml__getChildContent(xml,'RequestID'));
              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.
        Exit;
      end;
    if (success <> True) then
      begin
        Memo1.Lines.Add('Expected a well-formed XML response.');
        Exit;
      end;
    if (CkXml__tag(xml) <> 'DescribeInstanceStatusResponse') then
      begin
        Memo1.Lines.Add('Unexpected EC2 response element.');
        Exit;
      end;
    if ((CkXml_HasChildWithTag(xml,'requestId') <> True) or (CkXml__getChildContent(xml,'requestId') = '')) then
      begin
        Memo1.Lines.Add('Missing or empty requestId.');
        Exit;
      end;
    Memo1.Lines.Add('AWS request ID: ' + CkXml__getChildContent(xml,'requestId'));
    if (CkXml_HasChildWithTag(xml,'instanceStatusSet') <> True) then
      begin
        Memo1.Lines.Add('Expected instanceStatusSet.');
        Exit;
      end;
    i := 0;
    while (i < CkXml_NumChildrenAt(xml,'instanceStatusSet')) do
      begin
        CkXml_putI(xml,i);
        if ((CkXml_HasChildWithTag(xml,'instanceStatusSet|item[i]|instanceId') <> True) or (CkXml__getChildContent(xml,'instanceStatusSet|item[i]|instanceId') = '')) then
          begin
            Memo1.Lines.Add('Missing or empty instanceStatusSet|item[i]|instanceId.');
            Exit;
          end;
        Memo1.Lines.Add('Instance: ' + CkXml__getChildContent(xml,'instanceStatusSet|item[i]|instanceId'));
        //  Read by element name; XML response element order is not guaranteed.
        if (CkXml_HasChildWithTag(xml,'instanceStatusSet|item[i]|availabilityZone') = True) then
          begin
            Memo1.Lines.Add('Availability Zone: ' + CkXml__getChildContent(xml,'instanceStatusSet|item[i]|availabilityZone'));
          end;
        if (CkXml_HasChildWithTag(xml,'instanceStatusSet|item[i]|instanceState|name') = True) then
          begin
            Memo1.Lines.Add('State: ' + CkXml__getChildContent(xml,'instanceStatusSet|item[i]|instanceState|name'));
          end;
        if (CkXml_HasChildWithTag(xml,'instanceStatusSet|item[i]|systemStatus|status') = True) then
          begin
            Memo1.Lines.Add('System health: ' + CkXml__getChildContent(xml,'instanceStatusSet|item[i]|systemStatus|status'));
          end;
        if (CkXml_HasChildWithTag(xml,'instanceStatusSet|item[i]|instanceStatus|status') = True) then
          begin
            Memo1.Lines.Add('Instance health: ' + CkXml__getChildContent(xml,'instanceStatusSet|item[i]|instanceStatus|status'));
          end;
        if (CkXml_HasChildWithTag(xml,'instanceStatusSet|item[i]|attachedEbsStatus|status') = True) then
          begin
            Memo1.Lines.Add('Attached EBS health: ' + CkXml__getChildContent(xml,'instanceStatusSet|item[i]|attachedEbsStatus|status'));
          end;
        if (CkXml_HasChildWithTag(xml,'instanceStatusSet|item[i]|applicationStatus|status') = True) then
          begin
            Memo1.Lines.Add('Application health: ' + CkXml__getChildContent(xml,'instanceStatusSet|item[i]|applicationStatus|status'));
          end;
        if (CkXml_HasChildWithTag(xml,'instanceStatusSet|item[i]|performanceStatus|status') = True) then
          begin
            Memo1.Lines.Add('Performance health: ' + CkXml__getChildContent(xml,'instanceStatusSet|item[i]|performanceStatus|status'));
          end;
        //  Scheduled events may be absent. Event IDs and timestamps remain strings.
        j := 0;
        while (j < CkXml_NumChildrenAt(xml,'instanceStatusSet|item[i]|eventsSet')) do
          begin
            CkXml_putJ(xml,j);
            if (CkXml_HasChildWithTag(xml,'instanceStatusSet|item[i]|eventsSet|item[j]|instanceEventId') = True) then
              begin
                Memo1.Lines.Add('Event ID: ' + CkXml__getChildContent(xml,'instanceStatusSet|item[i]|eventsSet|item[j]|instanceEventId'));
              end;
            if (CkXml_HasChildWithTag(xml,'instanceStatusSet|item[i]|eventsSet|item[j]|code') = True) then
              begin
                Memo1.Lines.Add('Event: ' + CkXml__getChildContent(xml,'instanceStatusSet|item[i]|eventsSet|item[j]|code'));
              end;
            if (CkXml_HasChildWithTag(xml,'instanceStatusSet|item[i]|eventsSet|item[j]|description') = True) then
              begin
                Memo1.Lines.Add('Description: ' + CkXml__getChildContent(xml,'instanceStatusSet|item[i]|eventsSet|item[j]|description'));
              end;
            if (CkXml_HasChildWithTag(xml,'instanceStatusSet|item[i]|eventsSet|item[j]|notBefore') = True) then
              begin
                Memo1.Lines.Add('Not before: ' + CkXml__getChildContent(xml,'instanceStatusSet|item[i]|eventsSet|item[j]|notBefore'));
              end;
            if (CkXml_HasChildWithTag(xml,'instanceStatusSet|item[i]|eventsSet|item[j]|notAfter') = True) then
              begin
                Memo1.Lines.Add('Not after: ' + CkXml__getChildContent(xml,'instanceStatusSet|item[i]|eventsSet|item[j]|notAfter'));
              end;
            if (CkXml_HasChildWithTag(xml,'instanceStatusSet|item[i]|eventsSet|item[j]|notBeforeDeadline') = True) then
              begin
                Memo1.Lines.Add('Rescheduling deadline: ' + CkXml__getChildContent(xml,'instanceStatusSet|item[i]|eventsSet|item[j]|notBeforeDeadline'));
              end;
            j := j + 1;
          end;

        i := i + 1;
      end;

    page := page + 1;
    more := False;
    nextToken := '';
    if (CkXml_HasChildWithTag(xml,'nextToken') = True) then
      begin
        nextToken := CkXml__getChildContent(xml,'nextToken');
      end;
    if (nextToken <> '') then
      begin
        if (CkHashtable_Contains(seenTokens,nextToken) = True) then
          begin
            Memo1.Lines.Add('Repeated pagination token; status enumeration is incomplete.');
            Exit;
          end;
        success := CkHashtable_AddInt(seenTokens,nextToken,1);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not track pagination.');
            Exit;
          end;
        //  Replace the prior token; do not accumulate duplicate NextToken parameters.
        if (page > 1) then
          begin
            success := CkRest_RemoveQueryParam(rest,'NextToken');
            if (success <> True) then
              begin
                Memo1.Lines.Add('Could not remove the previous pagination token.');
                Exit;
              end;
          end;
        success := CkRest_AddQueryParam(rest,'NextToken',nextToken);
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not set NextToken.');
            Exit;
          end;
        more := True;
      end;
  end;

Memo1.Lines.Add('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.

CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkHashtable_Dispose(seenTokens);