Skip to content

Instantly share code, notes, and snippets.

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 leberknecht/439d00884a5c49df57a087d49d867eac to your computer and use it in GitHub Desktop.
Save leberknecht/439d00884a5c49df57a087d49d867eac to your computer and use it in GitHub Desktop.
create hostname entries for docker containers on docker-hosts /etc/hosts
#!/bin/bash
args=("$@")
CONTAINER_IDS=$(docker ps | cut -d" " -f1 | tail -n +2)
cp /etc/hosts /tmp/hosts.bak
cp /etc/hosts /tmp/hosts.tmp
echo "etc/hosts backup saved to /tmp/hosts.bak"
for i in $CONTAINER_IDS; do
if [[ ${args[0]} == '' ]]; then
if [[ "$DOCKER_HOST" != "" ]]; then
ALL_IPS=($(echo $DOCKER_HOST | egrep '[0-9]+.[0-9]+.[0-9]+.[0-9]+' -o))
else
ALL_IPS=$(docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}},{{end}}' $i)
IFS=',' read -r -a ALL_IPS <<< "$ALL_IPS"
fi
else
ALL_IPS=(${args[0]})
fi
for IP in "${ALL_IPS[@]}"
do
CONTAINER_NAME=$(docker inspect --format '{{ .Name }}' $i | tail -c +2)
SERVICE_NAME=$(docker inspect $i | grep "com.docker.compose.service" | cut -d'"' -f4)
#@To-Do replace grep+cut with jq
VIRTUAL_HOSTS=$(docker inspect $i | egrep -i 'NGINX_HOST|VIRTUAL_HOST|VHOST' | cut -d"=" -f 2 | grep -o '[-A-Za-z\.,]*' | head -n1 | sed 's/,/ /g')
DOCKER_HOST_NAME=$(docker inspect $i | grep -i '"Hostname":' | cut -d ":" -f2 | sed 's/[^A-Za-z0-9_-]//g')
if [[ "$IP" != "" ]]; then
cat /tmp/hosts.tmp | grep -v "$VIRTUAL_HOSTS" > /tmp/hosts2.tmp
cat /tmp/hosts.tmp | egrep -v "$DOCKER_HOST_NAME|$CONTAINER_NAME|$IP\s+" > /tmp/hosts2.tmp
mv /tmp/hosts2.tmp /tmp/hosts.tmp
echo "$IP $SERVICE_NAME $CONTAINER_NAME $VIRTUAL_HOSTS $DOCKER_HOST_NAME" | tee -a /tmp/hosts.tmp
fi
done
done;
read -p "Update /etc/hosts (yY) ? " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
sudo cp /tmp/hosts.tmp /etc/hosts
echo "changes applied"
else
echo "changes dismissed"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment