Created
September 2, 2018 00:11
-
-
Save heph/d1abea9abde4cb0c77939cab12c35be2 to your computer and use it in GitHub Desktop.
Write chef node names and public ip addresses to /etc/hosts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -euo pipefail | |
HEADER='# All lines below managed by chef_hostfile.sh' | |
backup_hostsfile() { | |
sudo cp /etc/hosts{,.$(date +%s)} | |
} | |
write_hostsfile() { | |
[[ -z "$1" ]] && [[ ! -e "$1" ]] && echo "ERROR! Calling write_hostsfile() with invalid filename: $1" | |
if ! git diff /etc/hosts "$1"; then | |
read -p 'Overwrite /etc/hosts with this change? (y/N)' -n 1 -r | |
echo | |
if [[ $REPLY =~ ^[Yy]$ ]]; then | |
cat "$1" | sudo tee /etc/hosts > /dev/null | |
fi | |
fi | |
} | |
main() { | |
backup_hostsfile | |
local tmpfile=$(mktemp "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXXXX") | |
# strip everything after and including $HEADER into a new file | |
sed '/^'"${HEADER}"'/,$ d' /etc/hosts | tee "$tmpfile" | |
echo "$HEADER" | tee -a "$tmpfile" | |
while IFS=" " read -r ip name; do | |
echo "$(printf "%-16s%s\n" "$ip" "$name")" | tee -a "$tmpfile" | |
done <<< "$(knife search node 'cloud_public_ipv4:*' -a cloud.public_ipv4 -Fjson \ | |
| jq -r '.rows[]|to_entries|map("\(.value|."cloud.public_ipv4") \(.key)")|.[]' \ | |
| sort -k 2 )" | |
write_hostsfile "$tmpfile" | |
rm "$tmpfile" | |
} | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment