Last active
January 13, 2022 09:55
-
-
Save harryjubb/5d2df0f7e54311911f97e11707faf034 to your computer and use it in GitHub Desktop.
Generate TLS certificates with Let'sEncrypt using Cloudflare DNS validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Create / update Let'sEncrypt certificates for a domain. | |
# | |
# Requires certbot with the dns_cloudflare plugin to be installed. | |
# https://eff-certbot.readthedocs.io/en/stable/install.html | |
# | |
# For example, on Ubuntu: | |
# https://certbot.eff.org/instructions?ws=other&os=ubuntufocal | |
# See the "Wildcard" tab. | |
# | |
# Set $LE_DOMAIN and $LE_CLOUDFLARE_API_TOKEN on the command line, or in a | |
# .env file. | |
# | |
# E.g.: | |
# | |
# LE_DOMAIN=*.cressetsoftware.com | |
# LE_CLOUDFLARE_API_TOKEN=a_cloudflare_api_token | |
# | |
# The Cloudflare token needed by Certbot requires Zone:DNS:Edit permissions | |
# for only the zones you need certificates for. | |
# https://certbot-dns-cloudflare.readthedocs.io/en/stable/index.html | |
set -e | |
mkdir -p ./config | |
mkdir -p ./lib | |
mkdir -p ./log | |
mkdir -p ./certs | |
if [ -f .env ]; then | |
source .env | |
fi | |
LE_DOMAIN_SANITIZED=$(echo "$LE_DOMAIN" | sed 's/[*]/wildcard/g') | |
echo "dns_cloudflare_api_token = $LE_CLOUDFLARE_API_TOKEN" > ./cloudflare.ini | |
chmod 600 ./cloudflare.ini | |
# Use the staging server while testing the script to avoid rate limits | |
# By adding: --test-cert \ | |
certbot certonly \ | |
--work-dir . \ | |
--dns-cloudflare \ | |
--dns-cloudflare-propagation-seconds 10 \ | |
--dns-cloudflare-credentials ./cloudflare.ini \ | |
--config-dir ./config \ | |
--work-dir ./lib \ | |
--logs-dir ./log \ | |
-d "$LE_DOMAIN" | tee ./le.log | |
FULLCHAIN=$(grep '^Certificate is saved at' le.log | sed 's/^.*at://g' | sed 's/^ *//g') | |
PRIVKEY=$(grep '^Key is saved at' le.log | sed 's/^.*at://g' | sed 's/^ *//g') | |
EXPIRY=$(grep '^This certificate expires on' le.log | sed 's/^.*on //g' | sed 's/^ *//g' | sed 's/\.$//g') | |
FULLCHAIN_COPY="./certs/$LE_DOMAIN_SANITIZED-fullchain-$EXPIRY.crt" | |
PRIVKEY_COPY="./certs/$LE_DOMAIN_SANITIZED-privkey-$EXPIRY.pem" | |
cp "$FULLCHAIN" "$FULLCHAIN_COPY" | |
cp "$PRIVKEY" "$PRIVKEY_COPY" | |
rm cloudflare.ini | |
echo | |
echo "Certificate keypair copied for convenience:" | |
echo "$FULLCHAIN_COPY" | |
echo "$PRIVKEY_COPY" | |
echo | |
echo "Certbot copies:" | |
echo "$FULLCHAIN" | |
echo "$PRIVKEY" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment