Last active
January 18, 2019 20:56
-
-
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).
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
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