Last active
February 28, 2018 00:26
-
-
Save jopecko/8c6c80f5ff71c13dffe3b9b92b55a5cd to your computer and use it in GitHub Desktop.
AWS SSH config generation
This file contains hidden or 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
#!/usr/bin/env python | |
import boto.ec2 | |
import os | |
def main(): | |
defaultUser = 'jopecko' | |
userHome = os.getenv('USERPROFILE') or os.getenv('HOME') | |
defaultKeyPath = os.path.join(userHome, '.ssh') | |
for region in boto.ec2.regions(): | |
try: | |
conn = boto.ec2.connect_to_region(region.name) | |
reservations = conn.get_all_instances() | |
instanceData = [] | |
for reservation in reservations: | |
for instance in reservation.instances: | |
# Check for User tag | |
if 'User' in instance.tags: | |
user = instance.tags['User'] | |
else: | |
user = defaultUser | |
# Check for Name tag | |
if 'Name' in instance.tags: | |
name = instance.tags['Name'] | |
else: | |
name = instance.id | |
if instance.public_dns_name: | |
dns = instance.public_dns_name | |
else: | |
dns = '{}.{}.nitro.us'.format(name, ('').join([x[0] for x in region.name.split('-')])) | |
instanceData.append((name, dns, user, user)) | |
# generate .ssh/config output | |
for data in instanceData: | |
print """Host {0} | |
HostName "{1}" | |
User {2} | |
IdentityFile {3} | |
UserKnownHostsFile=/dev/null | |
ServerAliveInterval 60 | |
StrictHostKeyChecking no | |
""".format(data[0], data[1], data[3], os.path.join(defaultKeyPath, "{0}.pem".format(data[2]))) | |
except: | |
pass | |
if __name__ == "__main__": | |
main() |
This file contains hidden or 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
# generate_aws_ssh_config.py > $HOME/.ssh/config_files/aws.sshconfig | |
alias compile-ssh-config='cat ~/.ssh/config_files/*.sshconfig >| ~/.ssh/compiled-config' | |
alias ssh='ssh -F ~/.ssh/compiled-config' | |
alias awsssh="ssh -F $HOME/.ssh/config_aws" | |
if [ -f "$HOME/.ssh/compiled-config" ]; then | |
complete -W \ | |
"$(cat ~/.ssh/compiled-config | grep '^Host' | cut -f 2 -d ' ' | uniq)" \ | |
ssh | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Provided you have
python
and theboto
package installed along with your$HOME/.aws/credentials
set up:Add the snip above to your
.bashrc
and 💰 from the autocompletion of hostnames using theawsssh
alias.