Last active
August 29, 2015 14:16
-
-
Save nickrw/63d87bd1459d26cf5757 to your computer and use it in GitHub Desktop.
resolve-ec2 - turns command line parameters into IP addresses (Name tags or instance IDs). Intended to be used in conjunction with ssh-ec2 and mux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from boto import ec2 | |
from functools import wraps | |
import re | |
def ip4(wrapped_func): | |
def _dec(request, *args, **kwargs): | |
response = wrapped_func(request, *args, **kwargs) | |
return [i.private_ip_address for i in response] | |
return wraps(wrapped_func)(_dec) | |
class AWSResolver(object): | |
def __init__(self, region='eu-west-1'): | |
self.region = region | |
self.ec2 = ec2.connect_to_region(self.region) | |
@ip4 | |
def instance_by_name_tag(self, tag): | |
return self.ec2.get_only_instances(filters={'tag:Name': tag}) | |
@ip4 | |
def instance_by_id(self, instance_id): | |
return self.ec2.get_only_instances(instance_id) | |
def resolve(self, *instance_spec): | |
matchers = { | |
r'^i-[a-f0-9]+$': self.instance_by_id, | |
r'.*': self.instance_by_name_tag | |
} | |
results = [] | |
for inst in instance_spec: | |
for pattern, resolver in matchers.iteritems(): | |
if re.match(pattern, inst): | |
results.extend(resolver(inst)) | |
break | |
return results | |
a = AWSResolver() | |
import sys | |
query = sys.argv | |
query.pop(0) | |
print '\n'.join(a.resolve(*query)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment