Skip to content

Instantly share code, notes, and snippets.

@garlandkr
Last active August 29, 2015 14:07
Show Gist options
  • Save garlandkr/657af0da48f550335faa to your computer and use it in GitHub Desktop.
Save garlandkr/657af0da48f550335faa to your computer and use it in GitHub Desktop.
Write EC2 hosts to ssh_config
"""
First generate the hosts.yaml file using the ec2.py inventory script.
./inventory/ec2.py --refresh-cache > hosts.yaml
"""
import os
import yaml
user = "ec2-user"
config = "/home/"+user+"/.ssh/config"
hosts = open("hosts.yaml", 'r')
hosts_yaml = yaml.load(hosts)
# Add any static hosts to the config first.
ssh_config = open(config, 'w')
write_line = "Host %s\nUser %s\nHostname %s\nIdentityFile ~/.ssh/%s\n\n" % (
"github.com",
"git",
"github.com",
"id_rsa")
ssh_config.write(write_line)
ssh_config.close()
# Open the dynamic hosts file and look at each host
for host in hosts_yaml['_meta']['hostvars']:
# Check to see if our host has a public or private address
if hosts_yaml['_meta']['hostvars'][host]['ec2_dns_name'] != "":
write_line = "\nHost %s\nUser %s\nHostname %s\nIdentityFile ~/.ssh/%s\n\n" % (
hosts_yaml['_meta']['hostvars'][host]['ec2_dns_name'],
user,
hosts_yaml['_meta']['hostvars'][host]['ec2_dns_name'],
hosts_yaml['_meta']['hostvars'][host]['ec2_key_name'])
elif hosts_yaml['_meta']['hostvars'][host]['ec2_private_dns_name'] != "":
write_line = "\nHost %s\nUser %s\nHostname %s\nIdentityFile ~/.ssh/%s\n\n" % (
hosts_yaml['_meta']['hostvars'][host]['ec2_private_dns_name'],
user,
hosts_yaml['_meta']['hostvars'][host]['ec2_private_dns_name'],
hosts_yaml['_meta']['hostvars'][host]['ec2_key_name'])
else:
# If we couldn't determine the ip address we write the instance id instead.
write_line = "\nHost %s\n\n" % hosts_yaml['_meta']['hostvars'][host]['ec2_id']
# Write the config line
ssh_config = open(config, 'a')
ssh_config.write(write_line)
ssh_config.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment