Skip to content

Instantly share code, notes, and snippets.

@heph
Created September 2, 2018 00:11
Show Gist options
  • Save heph/d1abea9abde4cb0c77939cab12c35be2 to your computer and use it in GitHub Desktop.
Save heph/d1abea9abde4cb0c77939cab12c35be2 to your computer and use it in GitHub Desktop.
Write chef node names and public ip addresses to /etc/hosts
#!/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