Generate SSH config file for your AWS instances

you have plenty of application instances running in a region and you quickly want to connect to one of them.

so, you log in to console, select the region, click on instance get the IP address (or right-click and get copy connect string), come back to your terminal and type (or paste)

ssh -i `whereverPAthtoMyFIleIs` ubuntu/ec2-user@someip 

what if you messed up writing the wrong path. well at least I had some problems before while following this naive approach, so I read about something called host config for ssh that you pre-write the path to file and all the details needed to connect to the instance

something like

Host my_instance
        HostName 11.50.84.89
        user ubuntu
        IdentityFile ~/my/path/to/pem

and store it in by default in ~/.ssh/config file .. well now you can just do

ssh my_instance

well I was greedy, I wanted to connect all the instances whenever I want to, without having to write them one time or go back to console and get the string for that matter

so I give you :P ( the dirty code )

import boto3
ec2=boto3.resource('ec2',region_name="ap-southeast-1")
s3=boto3.resource('s3',region_name="ap-southeast-1")
instances=ec2.instances.filter()
e=boto3.client('ec2',region_name="ap-southeast-1")

pempath="~/Downloads/pems/" #you might want to change this 
file=open('config.txt','w')
for i in instances:
    if( i.public_ip_address != None):
        user='ec2-user'
        if(e.describe_images(ImageIds=(str(i.image.image_id),))).get('Images')[0].get('Name').split('/')[0]=='ubuntu':
            user='ubuntu'
        print(f'Host {[j["Value"] for j  in i.tags if j["Key"]=="Name"][0]}\n\tHostName {i.public_ip_address}\n\tuser {user}\n\tIdentityFile {pempath}{i.key_pair.key_name}.pem\n')
        file.write(f'Host {[j["Value"] for j  in i.tags if j["Key"]=="Name"][0]}\n\tHostName {i.public_ip_address}\n\tuser {user}\n\tIdentityFile {pempath}{i.key_pair.key_name}.pem\n')
file.close()

this BOTO3 code generate the host config file for all your amzon-linux, ubuntu machine running in a region ( yeah I hardcoded the region, change it to your wish)

Assumption:

Each of your instances must be tagged with unique 'Name' else, how will u know which one to connect to? :)

PREREQUISITES:

you have aws_cli setup with proper keys and access to ec2 for instances

python3* is installed

boto3 package is installed

EXECUTION:

  1. copy the code to a file, name it anything u want ( i will name it hostconfig.py)

  2. create an empty file named config.txt ( not necessary )

  3. execute command python hostconfig.py

voila, config.txt now has the host config ready

you can move it to ~/.ssh/config and execute the command

ssh my_unique_instance_Name #yeah, just a random name, you got the idea :)

NOTE: change the pem path to your absolute path in system where u store your private keys

Published By

DevOps AWS ☁️(CDA,CSA) | Python | Terraform | Packer | Docker | Jenkins | Ansible | ELK | Rancher | Kubernetes | Bash

Follow

Last updated

Was this helpful?