Sample code for 30+ languages & platforms
PHP ActiveX Requires Chilkat v11.6.0+

Amazon EC2: Retrieve and Decode Instance Console Output

See more Amazon EC2 Examples

Retrieve the latest available console output, decode the API's base64 field, and save its bytes to a new local file. This is console output, not an interactive shell or live log stream. Check the returned timestamp; output can be missing or delayed. Linux output is the instance console; Windows output includes recent system event log errors. Console logs may contain sensitive data. Use a private directory, serialize access to the output file, and interpret text with the guest's encoding if needed.

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:GetConsoleOutput. 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.

GetConsoleOutput reference

Chilkat PHP ActiveX Downloads

PHP ActiveX
<?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';
$success = $rest->AddQueryParam('Action','GetConsoleOutput');
if ($success != 1) {
    print 'Could not set Action.' . "\n";
    exit;
}

$success = $rest->AddQueryParam('InstanceId',$instanceId);
if ($success != 1) {
    print 'Could not set InstanceId.' . "\n";
    exit;
}

$success = $rest->AddQueryParam('Latest','true');
if ($success != 1) {
    print 'Could not set Latest.' . "\n";
    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 != 'GetConsoleOutputResponse') {
    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('instanceId') != 1) or ($xml->getChildContent('instanceId') == '')) {
    print 'Missing or empty instanceId.' . "\n";
    exit;
}

if ($xml->getChildContent('instanceId') != $instanceId) {
    print 'Unexpected instance ID in console response.' . "\n";
    exit;
}

if ($xml->HasChildWithTag('timestamp') == 1) {
    print 'Output timestamp: ' . $xml->getChildContent('timestamp') . "\n";
}

if ($xml->HasChildWithTag('output') != 1) {
    print 'Console output is not available yet.' . "\n";
    exit;
}

$encodedOutput = $xml->getChildContent('output');
if ($encodedOutput == '') {
    print 'Console output is empty.' . "\n";
    exit;
}

$consoleData = new COM("Chilkat.BinData");
$success = $consoleData->AppendEncoded($encodedOutput,'base64');
if ($success != 1) {
    print 'Could not decode console output.' . "\n";
    exit;
}

//  Preserve the original bytes. Do not print potentially sensitive console logs.
$files = new COM("Chilkat.FileAccess");
$outputFile = 'ec2-console-output.txt';
if ($files->FileExists3($outputFile) != 0) {
    print 'Output path already exists or is inaccessible. Choose a new private filename.' . "\n";
    exit;
}

$success = $consoleData->WriteFile($outputFile);
if ($success != 1) {
    print 'Could not save console output.' . "\n";
    exit;
}

print 'Saved decoded console bytes to ' . $outputFile . "\n";

?>