Created
May 4, 2016 15:45
-
-
Save AMeng/b8504c36eadb05000500bf2588fd0b33 to your computer and use it in GitHub Desktop.
Find EC2 Private IPs from DNS or ELB Name or Tag Name
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 argparse import ArgumentParser | |
from boto.ec2 import EC2Connection | |
from boto.ec2.elb import ELBConnection | |
from socket import gethostbyname | |
from sys import argv | |
class NodeLookup: | |
def __init__(self, query): | |
self.elb_connection = ELBConnection() | |
self.ec2_connection = EC2Connection() | |
for function in [self.search_by_elb_name, self.search_by_dns_entry, self.search_by_tag_name]: | |
try: | |
return function(query) | |
except: | |
pass | |
def search_by_dns_entry(self, dns_entry): | |
ip_address = gethostbyname(dns_entry) | |
try: | |
elb_name = self.ec2_connection.get_all_network_interfaces(filters={'private_ip_address': ip_address})[0].description[4:] | |
except IndexError: | |
elb_name = self.ec2_connection.get_all_network_interfaces(filters={'association.public-ip': ip_address})[0].description[4:] | |
self.search_by_elb_name(elb_name) | |
def search_by_elb_name(self, elb_name): | |
elb = self.elb_connection.get_all_load_balancers(load_balancer_names=[elb_name])[0] | |
ec2_nodes = self.ec2_connection.get_all_instances(instance_ids=[i.id for i in elb.instances]) | |
self.print_nodes(ec2_nodes) | |
def search_by_tag_name(self, tag_name): | |
ec2_nodes = self.ec2_connection.get_all_instances(filters={"tag:Name" : tag_name}) | |
self.print_nodes(ec2_nodes) | |
def print_nodes(self, nodes): | |
for ip in [i.instances[0].private_ip_address for i in nodes]: | |
print ip | |
if __name__ == '__main__': | |
parser = ArgumentParser(description='Find EC2 Private IP Addresses.') | |
parser.add_argument('query', type=str, help='Search for EC2 nodes by any of: DNS, ELB Name, or Name Tag') | |
args = parser.parse_args() | |
lookup = NodeLookup(args.query) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment