Skip to main content

Helper script for acme.sh

Helper script for acme.sh

acme.sh is a client for generating Let's Encrypt certificates.
Certbot is a great alternative, but I've just stuck to what I know (hence why this exists).

This wiki page will just be backup for a GitHub Gist I've made: https://gist.github.com/Decicus/93d698347cf600af5ea822870eeef54c

#!/bin/bash

# Make sure to load environment variables.
. ~/.bashrc

ACME="/root/.acme.sh/acme.sh --force"
BASE="/srv/ssl"
ECHO_PREFIX="[acme.sh Helper Script]"

# Create directory if it exists, make sure permissions are as strict as possible.
echo "$ECHO_PREFIX Creating base certificate directory: $BASE"
mkdir -p $BASE
chmod -R 600 $BASE
chown -R root:root $BASE

echo "$ECHO_PREFIX Name of folder containing certificates? (Will be created under $BASE)"
read FOLDERNAME

echo "$ECHO_PREFIX Creating folder if it doesn't exist: $BASE/$FOLDERNAME"
mkdir -p "$BASE/$FOLDERNAME"

# ¯\_(ツ)_/¯ - https://timmurphy.org/2012/03/09/convert-a-delimited-string-into-an-array-in-bash/
OIFS=$IFS
IFS=' '

echo "$ECHO_PREFIX Space-separated list of domains to generate a certificate for?"
read DOMAIN_LIST

DOMAINS=($DOMAIN_LIST)
IFS=$OIFS
DOMAIN_PARAMS=""
ACME_PARAMS=""

for (( i = 0; i < ${#DOMAINS[@]}; i++ )); do
    DOMAIN_PARAMS+=" -d ${DOMAINS[$i]}"
done

echo "$ECHO_PREFIX DNS? [y/N]"
read IS_DNS

IS_DNS=${IS_DNS,,}
if [[ $IS_DNS == *"y"* ]]; then
    echo "$ECHO_PREFIX DNS provider? For example: Cloudflare = dns_cf."
    echo "$ECHO_PREFIX Provider also assumes the proper environment variables are set. Read: https://github.com/Neilpang/acme.sh/tree/master/dnsapi#how-to-use-dns-api"
    read DNS_PROVIDER

    ACME_PARAMS+="--dns $DNS_PROVIDER"
else
    echo "$ECHO_PREFIX Webroot? For example: /var/www/html"
    read WEBROOT_DIR

    ACME_PARAMS+="-w $WEBROOT_DIR"
fi

echo "$ECHO_PREFIX Reload command? For example: nginx -s reload"
read RELOADCMD

echo "$ECHO_PREFIX Requesting certificate using the chosen methods:"
eval "$ACME $DOMAIN_PARAMS $ACME_PARAMS --issue"

SSL_PATH="$BASE/$FOLDERNAME"
if [[ "$?" == "0" ]]; then
    echo "$ECHO_PREFIX Certificate request completed. Installing certificate with reload command."
    eval "$ACME $DOMAIN_PARAMS --key-file $SSL_PATH/key.pem --fullchain-file $SSL_PATH/fullchain.pem --cert-file $SSL_PATH/cert.pem --reloadcmd '$RELOADCMD' --install-cert"
else
    echo "$ECHO_PREFIX An error occurred during certificate request. Aborting."
fi