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.

Revisions

  1. adionditsak created this gist Feb 12, 2016.
    47 changes: 47 additions & 0 deletions generatehostsfile.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    #!/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