Skip to content

Instantly share code, notes, and snippets.

@barnybug
Created September 9, 2012 19:17
Show Gist options
  • Save barnybug/3686635 to your computer and use it in GitHub Desktop.
Save barnybug/3686635 to your computer and use it in GitHub Desktop.
Script to name all ec2 instances after the node name allocated to the elasticsearch running on that instance.
#!/usr/bin/python
# Script to name all ec2 instances after the node name allocated to the
# elasticsearch running on that instance. This makes it easy to track back
# to the physical system from visualization tools like bigdesk and head.
#
# Run directly on any elasticsearch node or port forward 9200 to a node in the
# cluster. Simple run without arguments:
# ./ec2names.py
#
# For further configuration, see help:
# ./ec2names.py --help
#
# Suggest croning the script to keeps the names in sync over restarts and new
# nodes.
#
# EC2 credentials are taken from the environment variables:
# AWS_ACCESS_KEY_ID
# AWS_SECRET_ACCESS_KEY
# EC2_REGION
#
# Use in conjunction with ec2-ssh for ssh coolness:
# http://github.com/Instagram/ec2-ssh
#
# (c) 2012 Barnaby Gray
import os
import sys
import boto.ec2
import urllib2
import json
import optparse
import string
import re
def main():
parser = optparse.OptionParser()
parser.add_option('--es', help='host:port of an elasticsearch node', default='localhost:9200')
parser.add_option('--template', help='template for name', default='$name')
parser.add_option('--group', help='limit to security group(s), eg. group1,group2')
(options, args) = parser.parse_args()
# first ask elasticsearch for node info
resp = urllib2.urlopen('http://%s/_cluster/nodes' % options.es)
nodes = json.load(resp)
t = string.Template(options.template)
re_addr = re.compile(r'inet\[/(.+):.+\]')
ip_to_name = {}
for node in nodes['nodes'].itervalues():
m = re_addr.match(node['transport_address'])
if m:
ip_to_name[m.group(1)] = t.safe_substitute(node)
# now the ec2 magic
region = os.getenv('EC2_REGION')
if not region:
print 'Please set environment variable EC2_REGION.'
print 'eg: export EC2_REGION=eu-west-1'
sys.exit(-1)
ec2 = boto.ec2.connect_to_region(region)
filters = {}
if options.group:
filters['group-name'] = options.group.split(',')
for r in ec2.get_all_instances(filters=filters):
for inst in r.instances:
name = ip_to_name.get(inst.private_ip_address)
if name and inst.tags.get('Name') != name:
inst.add_tag('Name', name)
print 'Set Name: %s on instance %s' % (name, inst.id)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment