Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Using the AWS PHP SDK to find running nodes by tag value
<?php
require 'aws.phar';
//===================================================================
// Readme:
//===================================================================
// To populate hostnames based on current live values, look up from AWS directly.
// Requires:
// - aws.phar in same folder as this script, or full path specified in the above require
// - IAM role assigned to node that allows Get* for ec2
//
// See https://docs.aws.amazon.com/aws-sdk-php/v3/guide/getting-started/installation.html#installing-via-phar for how to get the aws.phar file
//
// In the "Set Nodes" block, always specify index [0] to ensure only one name comes back (prod farms have multiple nodes)
//===================================================================
//===================================================================
// Set up connection:
//===================================================================
$ec2 = new Aws\Ec2\Ec2Client([
'version' => 'latest',
'region' => 'us-east-1'
]);
//===================================================================
// Get Nodes - retrieves all nodes matching said filters
//===================================================================
$dev_nodes = $ec2->describeInstances([
'Filters' => [
[
'Name' => 'tag:Group',
'Values' => ['myfancyappdev']
]
]
]);
$qa_nodes = $ec2->describeInstances([
'Filters' => [
[
'Name' => 'tag:Group',
'Values' => ['myfancyappqa']
]
]
]);
$prod_nodes = $ec2->describeInstances([
'Filters' => [
[
'Name' => 'tag:Group',
'Values' => ['myfancyappprod']
]
]
]);
//===================================================================
// Set Nodes - assign public DNS of first node to var to use later
//===================================================================
$dev = $dev_nodes['Reservations'][0]['Instances'][0]['PublicDnsName'];
$qa = $qa_nodes['Reservations'][0]['Instances'][0]['PublicDnsName'];
$prod = $prod_nodes['Reservations'][0]['Instances'][0]['PublicDnsName'];
//===================================================================
// environment dev
$aliases['dev'] = array(
'remote-host' => $dev,
);
// environment qa
$aliases['qa'] = array(
'remote-host' => $qa,
);
// prod
$aliases['prod'] = array(
'remote-host' => $prod,
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment