Skip to content

Commit

Permalink
Merge pull request #7 from the-kbA-team/6-can-not-extract-correct-hos…
Browse files Browse the repository at this point in the history
…tnames-in-docker-v16

extract correct hostnames for docker >= v26.x #6
  • Loading branch information
gregor-j authored Mar 25, 2024
2 parents ce7dfbb + 0b83775 commit 0212c7f
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions bin/docker_hosts.sh
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@

HOSTSFILE="/etc/hosts"
BUSYBOX="busybox:latest"
HOSTS_FORMAT='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{range .Aliases}} {{.}}{{end}}{{printf "\n"}}{{end}}'
HOSTS_FORMAT_ALIAS='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{range .Aliases}} {{.}}{{end}}{{printf "\n"}}{{end}}'
HOSTS_FORMAT_DNS_NAMES='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{range .DNSNames}} {{.}}{{end}}{{printf "\n"}}{{end}}'

set -e

Expand All @@ -20,6 +21,19 @@ show_usage() {
echo "Usage: docker_hosts.sh [-f <hosts-file>] [-r]"
}

extract_names() {
CONTAINER=$1

# try to fetch DNSNames node first. Available since docker version 26.x
DNS_NAMES=$(docker inspect --format "${HOSTS_FORMAT_DNS_NAMES}" "${CONTAINER}" 2>/dev/null)
if [ -z "${DNS_NAMES}" ]; then
# get aliases node
docker inspect --format "${HOSTS_FORMAT_ALIAS}" "${CONTAINER}"
else
echo "${DNS_NAMES}"
fi
}

# check if there is an environment variable that sets a different docker registry
if [ -n "${DOCKER_REGISTRY}" ]; then
BUSYBOX="${DOCKER_REGISTRY}/${BUSYBOX}"
Expand Down Expand Up @@ -69,7 +83,7 @@ if [ "${ADD_HOSTS:-1}" = "1" ]; then
# List all docker containers started by docker-compose
docker-compose ps -q | while read -r container; do
# Extract IP and hostnames from each container
docker inspect --format "${HOSTS_FORMAT}" "${container}";
extract_names "${container}";
# remove empty lines and append all lines to the hosts-file
done | awk "NF" | docker run --rm -i -v "${HOSTSFILE}":/tmp/h "${BUSYBOX}" tee -a /tmp/h
fi

0 comments on commit 0212c7f

Please sign in to comment.