Skip to content

Instantly share code, notes, and snippets.

@hoegaarden
Created May 17, 2024 08:14
Show Gist options
  • Save hoegaarden/e817986e34023b69c576f48b61e89ec9 to your computer and use it in GitHub Desktop.
Save hoegaarden/e817986e34023b69c576f48b61e89ec9 to your computer and use it in GitHub Desktop.
withHosts.sh
#!/usr/bin/env bash
# Runs a command with a modified /etc/hosts file.
# The modified file is created by adding the contents of the WITH_HOSTS, which
# is in the form of "name dest" pairs, separated by newlines.
#
# Usage:
#
# WITH_HOSTS=$'some.host localhost' \
# withHosts curl -v https://some.host/
#
# WITH_HOSTS=$'some.host localhost \n some.other.host google.com' \
# withHosts curl -v https://some.other.host/
set -e
set -u
set -o pipefail
readonly HOSTS_FILE='/etc/hosts'
main() {
local fd
exec {fd}< <(genHostsFile "${HOSTS_FILE}")
exec bwrap --dev-bind / / --ro-bind-data "${fd}" "${HOSTS_FILE}" "$@"
}
genHostsFile() {
local name dest ip
if [[ -n "${WITH_HOSTS:-}" ]]; then
echo '## > withHosts: additional hosts'
while read -r name dest ; do
if [[ -z "${name}" ]]; then
echo >&2 "# withHosts: skipping host entry for '${name}' -> '${dest}'"
continue
fi
if [[ -z "${dest}" ]]; then
echo >&2 "# withHosts: skipping host entry for '${name}' -> '${dest}'"
continue
fi
ip="$(getent ahosts "${dest}" | awk '{print $1; exit;}' || true)"
if [[ -z "${ip}" ]]; then
echo >&2 "# withHosts: skipping host entry for '${name}' -> '${dest}' (${ip:-?})"
continue
fi
echo >&2 "# withHosts: adding host entry for '${name}' -> '${dest}' (${ip})"
echo "${ip} ${name}"
done <<< "${WITH_HOSTS}"
echo '## < withHosts'
echo
fi
# cat the original /etc/hosts file
cat "$@"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment