Skip to content

Instantly share code, notes, and snippets.

@forbesmyester
Last active August 29, 2015 14:22
Show Gist options
  • Save forbesmyester/c10f72d56646b833aa4f to your computer and use it in GitHub Desktop.
Save forbesmyester/c10f72d56646b833aa4f to your computer and use it in GitHub Desktop.
Adds hosts which are generated for `https://github.com/jwilder/nginx-proxy` to your local /etc/hosts file (tested in Ubuntu)
#!/bin/bash
export DOCKER_GEN_VERSION="0.3.9"
# Generates a new /etc/hosts whenever a docker host is added with a VIRTUAL_HOST environmental variable ( see super useful project at https://github.com/jwilder )
# Code here shamelessly stolen from
# * https://github.com/jwilder/nginx-proxy/blob/master/Dockerfile
# * http://unix.stackexchange.com/questions/81685/how-to-remove-multiple-newlines-at-eof
if [ "$1" == "install" ]; then
wget https://github.com/jwilder/docker-gen/releases/download/$DOCKER_GEN_VERSION/docker-gen-linux-amd64-$DOCKER_GEN_VERSION.tar.gz && tar -C ~/.vendor/bin/ -xvzf docker-gen-linux-amd64-$DOCKER_GEN_VERSION.tar.gz && rm docker-gen-linux-amd64-$DOCKER_GEN_VERSION.tar.gz
fi
cat /etc/hosts | grep -v '# .*nginx-proxy-dns$' | awk '/^$/ {nlstack=nlstack "\n";next;} {printf "%s",nlstack; nlstack=""; print;}' > $TMP/nginx-proxy-dns-hosts.tpl
echo "" >> $TMP/nginx-proxy-dns-hosts.tpl
echo "" >> $TMP/nginx-proxy-dns-hosts.tpl
echo "# The following lines are managed by nginx-proxy-dns" >> $TMP/nginx-proxy-dns-hosts.tpl
echo "" >> $TMP/nginx-proxy-dns-hosts.tpl
echo '{{ range $host, $containers := groupBy $ "Env.VIRTUAL_HOST" }}' >> $TMP/nginx-proxy-dns-hosts.tpl
echo '{{ range $index, $value := $containers }}' >> $TMP/nginx-proxy-dns-hosts.tpl
echo '{{ with $address := index $value.Addresses 0 }}' >> $TMP/nginx-proxy-dns-hosts.tpl
# echo '{{ $address.IP }} {{ $host }} # nginx-proxy-dns' >> $TMP/nginx-proxy-dns-hosts.tpl
echo '127.0.0.1 {{ $host }} # nginx-proxy-dns' >> $TMP/nginx-proxy-dns-hosts.tpl
echo '{{ end }}' >> $TMP/nginx-proxy-dns-hosts.tpl
echo '{{ end }}' >> $TMP/nginx-proxy-dns-hosts.tpl
echo '{{ end }}' >> $TMP/nginx-proxy-dns-hosts.tpl
sudo ~/.vendor/bin/docker-gen -only-exposed -watch $TMP/nginx-proxy-dns-hosts.tpl /etc/hosts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment