Creating and using a free SSL certificate with Let's Encrypt

Generate certificate

With certbot installed within the emergence host environment:

sudo certbot certonly \
    --manual \
    --preferred-challenges=http \
    --manual-auth-hook emergence-certbot-auth \
    --manual-cleanup-hook emergence-certbot-cleanup \
    --agree-tos \
    --manual-public-ip-logging-ok \
    --non-interactive \
    --force-renewal \
    --domains "example.org,www.example.org,example.com,www.example.com" \
    --email "hello@example.org"

This will find the site under /emergence/sites for each domain and handle writing and cleaning up the .well-known/acme-challenge/* files.

Reconfigure site to use certificate

Once certificates are generated, you can patch the site config via filesystem API within the emergence host environment:

# change to the site handle for your target site
SITE_HANDLE=example

# confirm SITE_HANDLE and site configuration
sudo http \
    GET http+unix://%2Femergence%2Fkernel.sock/sites/${SITE_HANDLE}

# patch site configuration, reloading services as needed
sudo http \
    PATCH http+unix://%2Femergence%2Fkernel.sock/sites/${SITE_HANDLE} \
    'ssl:={
        "certificate": "/etc/letsencrypt/live/example.org/fullchain.pem",
        "certificate_key": "/etc/letsencrypt/live/example.org/privkey.pem"
    }'

Enable auto-renewal

Certbot can automatically renew all certificates every 3 months if the emergence host environment is running cron and certbot’s cron job is installed (which it is by default with the Ubuntu certbot package). In container environments, either create a docker exec cron job in the docker host environment or use Kubernetes CronJob to execute certbot’s scheduled nightly renew command within the emergence host environment

To ensure that certbot is equipped to make nginx reload certificates after certbot auto-renews them, this script should exist and be executable within the emergence host environment

/etc/letsencrypt/renewal-hooks/deploy/01-reload-nginx

#!/bin/bash -e

/usr/sbin/nginx -c /emergence/services/etc/nginx.conf -s reload

Ensure the script is executable:

sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/01-reload-nginx

Enable forced SSL redirection

If you’d like to force every page on your site to use https, add the follow configuration snippet at /php-config/Site.config.d/https.php

<?php

$onInitialized = Site::$onInitialized;

Site::$onInitialized = function () use ($onInitialized) {
    if (
        (array_key_exists('REQUEST_SCHEME', $_SERVER) && $_SERVER['REQUEST_SCHEME'] == 'http')
        || (array_key_exists('HTTPS', $_SERVER) && $_SERVER['HTTPS'] != 'on')
    ) {
        Site::redirect('https://' . Site::getConfig('primary_hostname') . $_SERVER['REQUEST_URI']);
    }

    if (is_callable($onInitialized)) {
        call_user_func($onInitialized);
    }
};

@chris I got an error when trying to use the cert.pem file as my .key file but the the privkey.pem worked.

1 Like