Skip to content

Instantly share code, notes, and snippets.

@wassname
Created January 15, 2016 00:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wassname/60b997d5f524f3123d49 to your computer and use it in GitHub Desktop.
Save wassname/60b997d5f524f3123d49 to your computer and use it in GitHub Desktop.
Bash script to update hostfile to mache docker-machines
#!/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