Skip to content

Instantly share code, notes, and snippets.

@mjbommar
Last active April 20, 2020 13:16
Show Gist options
  • Save mjbommar/4363524 to your computer and use it in GitHub Desktop.
Save mjbommar/4363524 to your computer and use it in GitHub Desktop.
Generate .ssh/config lines from EC2 instance information using boto.
'''
@author Bommarito Consulting, LLC
@date 2012-12-23
Generate .ssh/config lines from EC2 instance information.
'''
# Imports
import boto
import os
def main():
'''
Main method.
'''
# Default user
defaultUser = 'ubuntu'
# Default key path
userHome = os.getenv('USERPROFILE') or os.getenv('HOME')
defaultKeyPath = os.path.join(userHome, '.ssh')
# Connec to EC2; this assumes your boto config is in ~/.
ec2Connection = boto.connect_ec2()
# Get list of reservations.
reservationList = ec2Connection.get_all_instances()
# Initialize instance data tuple
instanceData = []
# Iterate over reservations
for reservation in reservationList:
# Iterate over instances
for instance in reservation.instances:
# Check for user tag
if 'user' in instance.tags:
user = instance.tags['user']
else:
user = defaultUser
# Check for name tag
if 'Name' in instance.tags:
name = instance.tags['Name']
else:
name = instance.id
instanceData.append((name, instance.public_dns_name, instance.key_name, defaultUser))
# Generate .ssh/config output
for data in instanceData:
print """Host {0}
HostName {1}
User {2}
IdentityFile {3}
""".format(data[0], data[1], data[3], os.path.join(defaultKeyPath, "{0}.pem".format(data[2])))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment