Bash script to update hostfile to mache docker-machines
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 | |
sethost () { # set up docker hostnames | |
# replace everything in line with the right IP, with $IP $MACHINE | |
D_MACHINE=$1 | |
echo "Update host file for machine=$D_MACHINE" | |
DATE=$(date -u +%s) | |
echo "backing up hosts to /tmp/hosts-$(date -u +%s)" | |
cp /etc/hosts /tmp/hosts-$(date -u +%s) | |
IP=$(docker-machine ip $D_MACHINE) | |
if [ -n "$IP" -a -n "$D_MACHINE" ]; then | |
OLD_LINE=$(egrep "\s$D_MACHINE$" /etc/hosts) | |
OLD_LINES=$(egrep "\s$D_MACHINE$" /etc/hosts -c) | |
NEW_LINE=$(sed "/\s$D_MACHINE$/ s/.*/$IP\t$D_MACHINE/g" /etc/hosts | egrep "\s$D_MACHINE$" ) | |
echo "change: $OLD_LINE => $NEW_LINE" | |
# check we found one old line | |
if [ $OLD_LINES -eq 1 ]; then | |
# replace in file | |
sudo sed -i "/\s$D_MACHINE$/ s/.*/$IP $D_MACHINE/g" /etc/hosts | |
else | |
if [ $OLD_LINES -eq 0 ]; then | |
# append to file | |
sudo echo "" | |
sudo sh -c "echo '$IP $D_MACHINE' >> /etc/hosts" > /dev/null | |
else | |
echo "multiple lines found, aborting" | |
fi | |
fi | |
else | |
echo "D_MACHINE=$D_MACHINE or IP=$IP not found" | |
fi | |
} | |
# update hostfile to point to named docker machines | |
for DMACHINE in $(docker-machine ls -q); do | |
sethost $DMACHINE | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment