Skip to content

Instantly share code, notes, and snippets.

@Havoc24k
Last active September 1, 2021 12:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Havoc24k/ec4b43cad0cf919d5f3c7796bb94a3b1 to your computer and use it in GitHub Desktop.
Save Havoc24k/ec4b43cad0cf919d5f3c7796bb94a3b1 to your computer and use it in GitHub Desktop.
Python script to generate an SSH config file for EC2 instances
#!/usr/bin/python
"""AWS EC2 SSH config Generator."""
import boto3
import os
# The location and name of our generated config file
path_to_config = '/.ssh/aws_demo.config'
# The SSH key we use to connet to those instances
path_to_ssh_key = "~/.ssh/aws_demo.pem"
# The SSH username to use
instance_username = 'ec2-user'
# The SSH port to connect to
ssh_port = 22
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>
User <instance_username>
port <ssh_port>
"""
for page in response_iterator:
for reservation in page['Reservations']:
for instance in reservation['Instances']:
try:
host_line = ""
host = ""
env = ""
if 'PublicIpAddress' in instance:
public_ip = instance['PublicIpAddress']
for tag in instance['Tags']:
if tag['Key'] == "Client":
client = tag['Value']
if tag['Key'] == "Name":
name = tag['Value']
if tag['Key'] == "Environment":
env = tag['Value']
host = "{}.{}.{}".format(
client, env, name).replace(" ", "-")
host_line += "##########################\n"
host_line += "host {}\n".format(host.lower())
host_line += " Hostname {}\n".format(public_ip)
host_line += " IdentityFile {}\n".format(
path_to_ssh_key)
host_line += " User {}\n".format(
instance_username)
host_line += " port {}\n".format(ssh_port)
host_line += "##########################\n"
host_line += "\n"
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