Last active
May 21, 2020 10:24
-
-
Save ryanellis/206ebe1e91fbc329de9e25c9f7236de9 to your computer and use it in GitHub Desktop.
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/sh | |
# filename: dockerhostsync.sh | |
# example usage: sudo ./dockerhostsync.sh /etc/hosts | |
processfile=$1 | |
tmpfile=${1}.tmp | |
backupfile=${1}.$(date "+%Y%m%d-%H%M%S").bak | |
# make a back-up | |
cp $processfile $backupfile | |
# loop all running docker containers | |
for service in `docker ps -q`; do | |
# extract the metadata we need | |
ipaddress=`docker inspect --format '{{ .NetworkSettings.Networks.nginx_easydev.IPAddress }}' $service` | |
servicename=`docker inspect --format '{{ .Name }}' $service ` | |
# optional metadata | |
hostname=`docker inspect --format '{{ .Config.Hostname }}' $service ` | |
domainname=`docker inspect --format '{{ .Config.Domainname }}' $service ` | |
fqdn=$hostname'.'$domainname | |
# make sure service name and ipaddresses aren't empty | |
if [[ -n $ipaddress ]] && [[ -n $servicename ]]; then | |
# remove the leading character ('/') | |
servicename=${servicename:1} | |
# remove any lines with the service name from the process file, so we can add it again | |
grep -v "$servicename" $processfile > $tmpfile | |
# start constructing the line we'll be adding | |
line=$ipaddress'\t'$servicename | |
# add FQDN if we have it | |
if [[ -n $domainname ]] && [[ -n $hostname ]]; then | |
line=$line' '$fqdn | |
fi | |
# append line to file | |
echo -e $line >> $tmpfile | |
# finally replace the processfile with our temporary one | |
mv $tmpfile $processfile | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment