Question

I have a bunch of EC2 instances that I've spun up using CloudFormation. I need to programmatically get the AWS instance_id for each of these hosts and would ideally like to do so without having to ssh into each of the hosts and gather that information. Is there an AWS API that will provide me with this functionality? Thanks!

Was it helpful?

Solution

There are several ways. The one I like best is putting an output section in your CloudFormation template with entries for each EC2 instance created by the template. Then you can fetch those results when you create the stack, either from the program output if you create the stack with a command line tool, or with the CloudFormation API.

You can also use the CloudFormation API to fetch a list of all created resources from a stack, or the EC2 API to get a list of all instances in a region and then filter them, perhaps by launch time.

Suppose your CloudFormation stack creates EC2 instances called Tom and Jerry. Then you would add an Outputs section something like the following:

"Outputs": {
    "TomId": {
        "Description": "Tom's instance id",
        "Value": {"Ref": "Tom"}
    },
    "JerryId": {
        "Description": "Jerry's instance id",
        "Value": {"Ref": "Jerry"}
    }
}

If you create the stack from the console, there will be a tab for the stack's outputs, and that will have a table with the two instance IDs included in it. Most command-line tools for creating a stack will also have some way of including the outputs.

But you asked for how to do it programmatically. Here's an example in Python, using the excellent boto library:

import boto.cloudformation
cf = boto.cloudformation.connect_to_region('us-east-1', aws_access_key_id='MyAccessKey', aws_secret_access_key='MySecretKey')
stacks = cf.describe_stacks('MyStackName')
stack = stacks[0]
for output in stack.outputs:
    print "%s: %s" % (output.key, output.value)

Note that the describe_stacks method returns an array of matching stacks. There should be only one, but you can check that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top