github.com/drud/ddev@v1.21.5-alpha1.0.20230226034409-94fcc4b94453/containers/ddev-router/gen-cert-and-nginx-config.sh.tmpl (about)

     1  #!/bin/bash
     2  
     3  # This gets preprocessed by docker-gen into a script which generates needed
     4  # mkcert certs and updates the nginx configs for all projects
     5  
     6  set -eu -o pipefail
     7  
     8  {{/* Output details about each container into the output script file */}}
     9  {{/* Not only is this good for debugging, but it makes the output file */}}
    10  {{/* unique so that docker-gen won't fail to update it if any of these details change */}}
    11  {{ range $host, $containers := groupByMulti $ "Env.VIRTUAL_HOST" "," }}
    12  {{ range $container := $containers }}
    13  # {{ $container.Name }} VIRTUAL_HOST={{ $container.Env.VIRTUAL_HOST }} HTTP_EXPOSE={{ $container.Env.HTTP_EXPOSE }} HTTPS_EXPOSE={{ $container.Env.HTTPS_EXPOSE }}
    14  {{ end }}
    15  {{ end }}
    16  
    17  hostnames='{{ range $host, $containers := groupByMulti $ "Env.VIRTUAL_HOST" "," }}{{ trim $host }} {{ end }}'
    18  echo "Processing certs and nginx for hostnames: $hostnames"
    19  
    20  # To redirect invalid hostnames, we need a list of http ports and https ports
    21  httpports='80
    22  {{ range $port, $containers := groupByMulti $ "Env.HTTP_EXPOSE" "," }}{{ trim $port }}
    23  {{ end }}'
    24  echo "${httpports}" >/tmp/httpports.txt
    25  httpsports='443
    26  {{ range $port, $containers := groupByMulti $ "Env.HTTPS_EXPOSE" "," }}{{ trim $port }}
    27  {{ end }}'
    28  echo "${httpsports}" >/tmp/httpsports.txt
    29  
    30  # Convert the lists into unique sets of listen directives in /tmp
    31  awk -F: '$0 != "" {printf "\tlisten %s default_server;\n", $1;}' /tmp/httpports.txt | sort -u >/tmp/http_ports.conf
    32  awk -F: -v http2=${HTTP2} '$0 != "" {printf "\tlisten %s ssl %s default_server;\n", $1, http2;}' /tmp/httpsports.txt | sort -u >/tmp/https_ports.conf
    33  
    34  
    35  if [ ! -z "${USE_LETSENCRYPT:-}" ]; then
    36    for host in ${hostnames}; do
    37      # certbot challenge can fail for many reasons, but don't let it break everything
    38      certbot --nginx certonly -n --domain "${host}" --agree-tos --email "${LETSENCRYPT_EMAIL:-}" || true
    39    done
    40  fi
    41  
    42  mkcert -cert-file /etc/nginx/certs/master.crt -key-file /etc/nginx/certs/master.key $hostnames 127.0.0.1 localhost "*.ddev.site"
    43  
    44  # This is not recursive, as it executes completely different instructions.
    45  # It's important for the nginx config creation and the nginx reload to take place after all cert
    46  # activities are completed.
    47  docker-gen -only-exposed -notify-output -notify "nginx -s reload" /app/nginx.tmpl /etc/nginx/conf.d/ddev.conf