Skip to content

Instantly share code, notes, and snippets.

@pgstenberg
Last active July 30, 2019 12:14
Show Gist options
  • Save pgstenberg/0204bd8467b8ea4bd3033ef11f51ff4e to your computer and use it in GitHub Desktop.
Save pgstenberg/0204bd8467b8ea4bd3033ef11f51ff4e to your computer and use it in GitHub Desktop.
Bash script with embedded python script that extract hosts entries and append them as docker --add-host flags during docker run
#!/bin/bash
#===============================================================================
# example usage:
# docker run -it --rm $(cat /etc/hosts | _add_host_flags) ubuntu /bin/bash
#
# Print content of docker hosts /etc/hosts, pipe it ./add-host.sh
# and echo all the necessary --add-host flags to the docker run command
#===============================================================================
_add_host_flags() {
read -r -d '' script <<-"EOF"
import re, sys
# RegExp pattern for matching all entries except default ones like 127.0.0.1 localhost, etc.
PATTERN = re.compile(r'^(?!127\.0\.0\.1|::1|f[ef]0[0|2]::[0-2])([a-zA-Z0-9\-\:\.]+)\s+([a-zA-Z0-9\.\-\s]+)$')
# Exit early if stdin was empty
if sys.stdin.isatty():
sys.exit()
for (idx0, line) in enumerate(sys.stdin):
z = re.match(PATTERN, line)
if z != None:
for (idx1, h) in enumerate(z.groups()[1].split()):
sys.stdout.write("%s--add-host %s:%s" % ((' ' if (idx0 or idx1) else ''), h, z.groups()[0]))
EOF
python -c "$script"
}
# Just some example with echo
echo "docker run -it --rm $(cat /etc/hosts | _add_host_flags) ubuntu /bin/bash"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment