Last active
December 10, 2024 12:02
-
-
Save celmaun/a30f0741ccdf6f804eef9a6f0db499af to your computer and use it in GitHub Desktop.
Installs docker container names and IP addresses in /etc/hosts https://x.com/Celmaun/status/1866434295805456807
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
#!/usr/bin/env bash | |
# vim:set ft=bash ts=4 sw=4 et : | |
# shellcheck shell=bash | |
# shellcheck disable=SC2317 | |
## Usage: | |
## docker-etc-hosts-install | |
## Installs docker container names and IP addresses in /etc/hosts | |
## This script is idempotent | |
## Note: Requires root privileges to write to /etc/hosts | |
## Example output written to /etc/hosts: | |
## #START_DOCKER_ETC_HOSTS# | |
## 192.168.97.16 caddy-1.localhost | |
## 192.168.97.15 www-1.localhost | |
## 192.168.215.2 portainer.localhost | |
## #END_DOCKER_ETC_HOSTS# | |
set -a | |
orex() { "$@" || exit "$?$(printf >&2 '^ ERROR[%d]: %s\n' "$?" "$*")"; } | |
oret() { "$@" || return "$?$(printf >&2 '^ ERROR[%d]: %s\n' "$?" "$*")"; } | |
sed_inplace() { | |
case $(sed --help 2>&1) in | |
*GNU*) sed -i "$@" || return ;; | |
*) sed -i '' "$@" || return ;; | |
esac | |
} | |
docker_etc_hosts_file() { | |
printf '%s\n' "/etc/hosts" | |
} | |
docker_etc_hosts_clear() { | |
orex sed_inplace '/#START_DOCKER_ETC_HOSTS#/,/#END_DOCKER_ETC_HOSTS#/d' "$(docker_etc_hosts_file)" | |
} | |
docker_etc_hosts_entries() { | |
# Docker prefixes container names with a slash | |
# First sed is to remove containers with empty IP (slash prefixed lines) | |
# Second sed replaces slash prefix in container names with spaces | |
printf '%s\n' "#START_DOCKER_ETC_HOSTS#" | |
docker ps -a --format "{{.Names}}" | | |
xargs -I {} sh -c 'docker inspect -f "{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}{{.Name}}.localhost" {}' | | |
sed '/^\//d' | | |
sed 's@/@ @g' | |
printf '%s\n' "#END_DOCKER_ETC_HOSTS#" | |
} | |
docker_etc_hosts_install() { | |
orex docker_etc_hosts_clear | |
docker_etc_hosts_entries >>"$(docker_etc_hosts_file)" | |
} | |
set +a | |
orex docker_etc_hosts_install |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment