Last active
October 30, 2020 14:14
-
-
Save memoryleak/48ea2e8229e9fedf74d56aa72aaed75c to your computer and use it in GitHub Desktop.
This file contains 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 python3 | |
# Simple Python script to lookup EC2 instance ip addresses based on the name tag. | |
import os | |
import argparse | |
import boto3 | |
from appdirs import user_cache_dir | |
from tabulate import tabulate | |
appname = "ec2query" | |
appauthor = "Haydar Ciftci" | |
cache_dir = user_cache_dir(appname, appauthor) | |
def update(): | |
client = boto3.client('ec2') | |
reservations = client.describe_instances() | |
if not os.path.exists(cache_dir): | |
os.mkdir(cache_dir) | |
cache_file = cache_dir + os.path.sep + "ec2instances" | |
with open(cache_file, 'w') as cache_file_open: | |
for reservation in reservations['Reservations']: | |
for instance in reservation['Instances']: | |
if instance['State']['Name'] != 'running': | |
continue | |
name = "" | |
for tag in instance['Tags']: | |
if tag['Key'] == 'Name': | |
name = tag['Value'] | |
if instance['PrivateIpAddress']: | |
cache_file_open.write("{}\t{}\n".format(name.lower(), instance['PrivateIpAddress'])) | |
print("Written cache to " + cache_file) | |
def search(name, update_cache=True): | |
if not os.path.exists(cache_dir): | |
update() | |
cache_file = cache_dir + os.path.sep + "ec2instances" | |
results = [] | |
for line in open(cache_file, 'r'): | |
if line.find(name) > -1: | |
results.append(line.strip().split("\t")) | |
if len(results) == 0 and update_cache: | |
update() | |
return search(name, False) | |
print(tabulate(results, headers=["Name", "Address"])) | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser(description='Search for EC2 instances') | |
parser.add_argument('name', type=str, nargs='?', help='Name of the EC2 instance') | |
args = parser.parse_args() | |
search(str(args.name).lower()) |
This file contains 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
boto3 | |
appdirs | |
tabulate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment