angrychimp
4/23/2019 - 9:56 PM

gen-ec2-ssh-config

Generate an SSH config file to pair EC2 instance IDs with private IP addresses

#!/bin/bash

IFS=$'\n'

key=$(uuidgen | cut -d- -f1)
touch /etc/ssh/config.d/.ids.$key
touch /etc/ssh/config.d/.names.$key

for region in us-west-1 us-west-2; do
for inst in $(aws --region $region ec2 describe-instances --query "Reservations[*].Instances[*].{Name:Tags[?Key==\`Name\`].Value|join(\`\`,@),ID:InstanceId,PrivateIP:PrivateIpAddress}" --output text); do
	id=$(echo "$inst" | awk -F"\t" '{print $1}')
	#name=$(echo "$inst" | awk -F"\t" '{print $2}')
	ip=$(echo "$inst" | awk -F"\t" '{print $3}')
	echo -e "Host $id\n    Hostname $ip" >> /etc/ssh/config.d/.ids.$key
	#echo -e "Host $name\n    Hostname $ip" >> /etc/ssh/config.d/.names.$key
done
done
cat /etc/ssh/config.d/.*.$key > /etc/ssh/config.d/ec2-hosts && rm /etc/ssh/config.d/.*.$key