Skip to content

Instantly share code, notes, and snippets.

@jbontech
Created April 21, 2020 03:44
Show Gist options
  • Save jbontech/b753a494a5829eaa0a1752eecef32304 to your computer and use it in GitHub Desktop.
Save jbontech/b753a494a5829eaa0a1752eecef32304 to your computer and use it in GitHub Desktop.
Create the ssh_config from for all the aws machines
#!/usr/bin/python
"""AWS EC2 SSH config Generator."""
import boto3
import os
import sys
# The location and name of our generated config file
path_to_config = '/.ssh/aws_demo'
# The SSH key we use to connet to those instances
path_to_ssh_key = "~/.ssh/xxx.pem"
def main():
"""Main."""
try:
"""
Using the security credentialsa and the location we set
when we run `$ awscli configure` we connect to AWS
and get the list of instances on the specific location
"""
aws_client = boto3.client('ec2')
paginator = aws_client.get_paginator('describe_instances')
response_iterator = paginator.paginate(
DryRun=False,
PaginationConfig={
'MaxItems': 100,
'PageSize': 10
}
)
"""
Open the config file we specified to be written
"""
ssh_config_file = open(os.path.expanduser(
'~') + path_to_config, 'w')
ssh_config_file.write("##########################\n")
ssh_config_file.write("##### AWS SSH CONFIG #####\n")
ssh_config_file.write("##########################\n\n")
"""
We iterate the results and read the tags for each instance.
Using those tags we create an ssh config entry for each instance.
and append it to the config file.
host <client>.<environment>.<name>
Hostname <ec2-public-ip>
IdentityFile <path_to_ssh_key>
"""
for page in response_iterator:
for reservation in page['Reservations']:
for instance in reservation['Instances']:
try:
host_line = ""
host = ""
env = ""
try:
public_ip = instance['PublicIpAddress']
except KeyError:
try:
public_ip = instance['PrivateIpAddress']
except KeyError:
sys.stderr.write(
'Cannot lookup ip address for instance %s,'
' skipped it.'
% instance['InstanceId'])
continue
for tag in instance['Tags']:
if tag['Key'] == "Name":
name = tag['Value']
host = "{}".format(name).replace(" ", "-")
host_line += "host {}\n".format(host.lower())
host_line += " Hostname {}\n".format(public_ip)
host_line += " IdentityFile {}\n".format(
path_to_ssh_key)
ssh_config_file.write(host_line)
except Exception as e:
raise e
print("File updated: " + os.path.expanduser('~') + path_to_config)
except Exception as e:
print(e)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment