Skip to content

Instantly share code, notes, and snippets.

@adionditsak
Created February 12, 2016 12:28
Show Gist options
  • Save adionditsak/c04f0c6ac6a152aea3de to your computer and use it in GitHub Desktop.
Save adionditsak/c04f0c6ac6a152aea3de to your computer and use it in GitHub Desktop.
Generate hosts file with AWS ec2 private IP's
#!/bin/bash
# Generate hosts-file with private IP's in AWS ec2
# Vars
hosts_file="/etc/hosts"
region="eu-west-1"
# AWS call
described_instances=`aws ec2 describe-instances --region ${region}`
# jq
private_ips=`echo $described_instances | jq '.Reservations[] .Instances[] .PrivateIpAddress' | tr -d \"`
hostnames=`echo $described_instances | jq '.Reservations[] .Instances[] .Tags[] | select(.Key == "hostname").Value' | tr -d \"`
# Associative array
declare -A arr
pcounter=0
for p in $private_ips
do
arr[0,$pcounter]=$p
let pcounter=pcounter+1
done
hcounter=0
for h in $hostnames
do
arr[1,$hcounter]=$h
let hcounter=hcounter+1
done
# Do your thing
counter=0
for i in $private_ips
do
found=`fgrep -c "${arr[1,${counter}]}" ${hosts_file}`
if [ $found -eq 0 ]; then
echo "${arr[0,${counter}]} ${arr[1,${counter}]}" >> /etc/hosts
else
sed -i "/${arr[1,${counter}]}/d" ${hosts_file}
echo "${arr[0,${counter}]} ${arr[1,${counter}]}" >> /etc/hosts
fi
let counter=counter+1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment