Skip to content

Instantly share code, notes, and snippets.

@akshendra
Last active December 10, 2017 15:30
Show Gist options
  • Save akshendra/0be787db45f9f89754a33ec70c251152 to your computer and use it in GitHub Desktop.
Save akshendra/0be787db45f9f89754a33ec70c251152 to your computer and use it in GitHub Desktop.
Generate ssh aliases for aws ec2 instances
#!/usr/bin/env python3
"""
Create ssh shortcut alias
"""
import boto3
ec2 = boto3.client('ec2')
SECRETS_DIR = '/Volumes/Booy/Secrets'
def extract_tags(tags):
required_tags = ['Name', 'type', 'role']
map = {
'Name': None,
'type': None,
'role': None,
}
for tag in tags:
key = tag['Key']
value = tag['Value']
if key in required_tags:
map[key] = value
return map
def extract_instance_data(instance):
"""Extract user full data for an instance"""
tag_map = extract_tags(instance['Tags'])
return {
'id': instance['InstanceId'],
'key': (instance['KeyName']
if 'KeyName' in instance
else None),
'ip': (instance['PublicIpAddress']
if 'PublicIpAddress' in instance
else None),
'name': tag_map['Name'],
'type': tag_map['type'],
'role': tag_map['role'],
}
def fetch_instances(response):
instances = []
for res in response['Reservations']:
instances.extend(res['Instances'])
return instances
def filter_instances(instances):
"""Filter all instances, if they don't have ip or name"""
filtered = []
for instance in instances:
if 'ip' not in instance or 'name' not in instance:
continue
if 'type' in instance and instance['type'] == 'none':
continue
if (instance['ip'] is not None and
instance['name'] is not None and
instance['type'] is not None):
filtered.append(instance)
return filtered
if __name__ == '__main__':
response = ec2.describe_instances(MaxResults=50)
extracted = [extract_instance_data(instance)
for instance in fetch_instances(response)]
instances = filter_instances(extracted)
for instance in instances:
print('alias {}="ssh -i {}/{}.pem ubuntu@{}"'
.format(instance['name'], SECRETS_DIR,
instance['key'], instance['ip']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment