Skip to content

Instantly share code, notes, and snippets.

@gngdb
Last active January 18, 2019 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gngdb/abc562dd3347d3eecd9be1fc6758bc47 to your computer and use it in GitHub Desktop.
Save gngdb/abc562dd3347d3eecd9be1fc6758bc47 to your computer and use it in GitHub Desktop.
Use boto3 to generate an ssh config file entry for all your running instances (checks to see if you've already added them as well).
import os
import boto3
if __name__ == '__main__':
session = boto3.Session()
ec2 = session.resource('ec2')
ec2c = session.client('ec2')
# add active instances to the user's ssh config file
instances = ec2.instances.filter(
Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
config = []
try:
config_path = os.path.join(os.environ['HOME'],".ssh/config")
with open(config_path, "r") as f:
old_config = f.read()
except FileNotFoundError:
old_config = ""
for instance in instances:
name = instance.tags[0]["Value"]
if name not in old_config:
config.append("# Generated for EC2 #")
config.append(f'Host {name}')
config.append(f' HostName {instance.public_ip_address}')
config.append(f' User ubuntu')
config.append(f' IdentityFile ~/.ssh/{instance.key_name}.pem')
config.append("# End Generated #")
print("\n".join(config))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment