Advertisement
Guest User

Untitled

a guest
Feb 12th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. # Generate hosts-file with private IP's in AWS ec2
  4.  
  5. # Vars
  6. hosts_file="/etc/hosts"
  7. region="eu-west-1"
  8.  
  9. # AWS call
  10. described_instances=`aws ec2 describe-instances --region ${region}`
  11.  
  12. # jq
  13. private_ips=`echo $described_instances | jq '.Reservations[] .Instances[] .PrivateIpAddress' | tr -d \"`
  14. hostnames=`echo $described_instances | jq '.Reservations[] .Instances[] .Tags[] | select(.Key == "hostname").Value' | tr -d \"`
  15.  
  16. # Associative array
  17. declare -A arr
  18.  
  19. pcounter=0
  20. for p in $private_ips
  21. do
  22. arr[0,$pcounter]=$p
  23. let pcounter=pcounter+1
  24. done
  25.  
  26. hcounter=0
  27. for h in $hostnames
  28. do
  29. arr[1,$hcounter]=$h
  30. let hcounter=hcounter+1
  31. done
  32.  
  33. # Do your thing
  34. counter=0
  35. for i in $private_ips
  36. do
  37. found=`fgrep -c "${arr[1,${counter}]}" ${hosts_file}`
  38.  
  39. if [ $found -eq 0 ]; then
  40. echo "${arr[0,${counter}]} ${arr[1,${counter}]}" >> /etc/hosts
  41. else
  42. sed -i "/${arr[1,${counter}]}/d" ${hosts_file}
  43. echo "${arr[0,${counter}]} ${arr[1,${counter}]}" >> /etc/hosts
  44. fi
  45.  
  46. let counter=counter+1
  47. done
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement