Skip to content

Instantly share code, notes, and snippets.

@kstromeiraos
Created September 10, 2018 11:51
Show Gist options
  • Save kstromeiraos/ea7c01af544d12cf5e5c4faab18c83ae to your computer and use it in GitHub Desktop.
Save kstromeiraos/ea7c01af544d12cf5e5c4faab18c83ae to your computer and use it in GitHub Desktop.
Python script to list EC2 running instances and their private IPs
#!/usr/bin/env python
'''
List EC2 running instances and their private IPs
'''
import boto3
import sys
from subprocess import call
import argparse
class Instance:
def __init__(self, name, ip):
self.name = name
self.ip = ip
def create_ec2_client(region):
return boto3.client('ec2', region_name=region)
def get_reservations(ec2_client):
return ec2_client.describe_instances(
Filters=[
{
'Name': 'instance-state-name',
'Values': ['running']
}
]
)
def get_instance_names_and_ips(reservations):
instance_list = []
for reservation in reservations['Reservations']:
for instance in reservation['Instances']:
for tag in instance['Tags']:
if tag['Key'] == 'Name':
instance_name = tag['Value']
instance_list.append(Instance(instance_name, instance['PrivateIpAddress']))
instance_list.sort(key=lambda x: x.name)
return instance_list
def print_ssh_instance_list(instances_list):
for instance in instances_list:
print(instance.name + ' -> ' + instance.ip)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('region', help="AWS region to list instances")
region = parser.parse_args().region
ec2_client = create_ec2_client(region)
reservations = get_reservations(ec2_client)
instances_list = get_instance_names_and_ips(reservations)
print_ssh_instance_list(instances_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment