Monday, July 28, 2014

ec2list -- quickly and easily list ec2 instances across all accounts and regions

Here's a quick tool I cooked up after working in with multiple AWS accounts in many regions. Sometimes I just need a particular piece of information about a host and I only had its instance id. Before this script I would have to run multiple aws calls in different regions until I found the instance.

The script itself is a wrapper around the aws cli tools. It will gather a list of instances in all accounts you specify and in all of the regions. It's multithreaded and I find it finishes in about 4 to 5 seconds. You'll get better performance if you comment out regions that you're not using.

Just clone the repo and execute.


usage: ec2list [-h] [-i INSTANCES] [-v] [-a] [-f FILTER]

optional arguments:
  -h, --help            show this help message and exit
  -i INSTANCES, --instances INSTANCES
                        Comma-separated list of instances to filter results.
  -v, --verbose         Print all host metadata.
  -a, --all             List all hosts, even those that aren't running.
  -f FILTER, --filter FILTER
                        key value filters to pass directly to command. Eg:


You must have a $HOME/.aws/config file setup with the proper credentials.
An example profile:
[profile production]

[profile staging]
You can test that the different profiles are active by running the aws cli tool
aws ec2 describe-instances --profile=production
aws ec2 describe-instances --profile=staging

Listing all instances in a succinct manner.

The columns when run this way will always be predictable (unlike -v). Useful if you're using awk or other things.
$ ./list
i-7e15d971 stephen_test_001 m3.large production
i-7e15d971 stephen_test_002 m3.large staging

List instances that are also stopped

By default only running instances will be shown. Use the -a or --all flag to show all instances, even those that are stopped.
$ ./list -a

Be verbose 

Verbose prints everything returned by ec2. The return values are unordered.
./list -v
  Monitoring: {"State": "disabled"}
  RootDeviceType: ebs
  State: {"Code": 16, "Name": "running"}
  EbsOptimized: False
  Monitoring: {"State": "disabled"}
  RootDeviceType: ebs
  State: {"Code": 16, "Name": "running"}
  EbsOptimized: False

Filter by a list of instance IDs

To easily filter instances by instance id, they can be passed as a comma-separated list with the -i or --instances flag.
./list -i i-bba5d6e6,i-cad1b0c2,i-afa406f2

Print only instances that are an m1.small, or other things

Note that the filters arg allows you to pass filters down directory to the underlying aws ec2 command. See the ec2 api for information on the types of filtering you can do.
$ ./list -f Name=instance-type,Values=m1.small

No comments:

Post a Comment