Skip to content

Instantly share code, notes, and snippets.

@jansendotsh
Last active September 23, 2020 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jansendotsh/c02af49ddf397c66561070b92330e554 to your computer and use it in GitHub Desktop.
Save jansendotsh/c02af49ddf397c66561070b92330e554 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Variables
DO_TOKEN=SANITIZED
EFF_EMAIL="garrett@jansen.sh"
CUSTOM_DOMAIN="s.jnsn.link"
CFLARE_EMAIL=SANITIZED
CFLARE_TOKEN=SANITIZED
# Check to see if certbot directories have been made here before
if [ ! -d "/data/certbot-cloudflare" ]
then
mkdir -p /data/certbot-cloudflare/{etc,log,var}
fi
# Checks for docker & jq
type docker >/dev/null 2>&1 || { echo >&2 "Docker not installed. Renewal failed." >> /data/certbot-cloudflare/log/cron.log; exit 1; }
type jq >/dev/null 2>&1 || { echo >&2 "jq not installed. Renewal failed." >> /data/certbot-cloudflare/log/cron.log; exit 1; }
# Create Cloudflare configuration
tee /data/certbot-cloudflare/etc/cloudflare.ini >/dev/null <<EOF
dns_cloudflare_email = $CFLARE_EMAIL
dns_cloudflare_api_key = $CFLARE_TOKEN
EOF
# Pull Docker container for certbot renewal with cloudflare
docker run --rm -it \
-v /data/certbot-cloudflare/etc:/etc/letsencrypt \
-v /data/certbot-cloudflare/var:/var/lib/letsencrypt \
-v /data/certbot-cloudflare/log:/var/log/letsencrypt \
certbot/dns-cloudflare certonly \
--dns-cloudflare \
--dns-cloudflare-credentials /etc/letsencrypt/cloudflare.ini \
--email $EFF_EMAIL --agree-tos --no-eff-email \
-d $CUSTOM_DOMAIN
# Upload cert & save ID (yes, the sed nonsense is necessary to replace newlines with characters
CERT_ID=$(curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer $DO_TOKEN" \
-d '{"name": "'"sjnsn-`date +%Y%m%d`"'", "type": "custom", "private_key": "'"$(sed -E ':a;N;$!ba;s/\r{0,1}\n/\\n/g' /data/certbot-cloudflare/etc/live/s.jnsn.link/privkey.pem)"'","leaf_certificate": "'"$(sed -E ':a;N;$!ba;s/\r{0,1}\n/\\n/g' /data/certbot-cloudflare/etc/live/s.jnsn.link/fullchain.pem)"'"}' \
"https://api.digitalocean.com/v2/certificates" | \
jq '.certificate.id' | \
sed -e 's/^"//' -e 's/"$//')
# Grab endpoint for the domain
ENDPOINT_ID=$(curl -X GET -H "Content-Type: application/json" \
-H "Authorization: Bearer $DO_TOKEN" \
"https://api.digitalocean.com/v2/cdn/endpoints" | \
jq '.endpoints[] | select(.custom_domain != null) | select(.custom_domain | contains("s.jnsn.link"))' | \
jq '.id' | \
sed -e 's/^"//' -e 's/"$//')
# Set new cert to endpoint
curl -X PUT -H "Content-Type: application/json" \
-H "Authorization: Bearer $DO_TOKEN" \
-d '{"certificate_id": "'"$CERT_ID"'","custom_domain": "'"$CUSTOM_DOMAIN"'"}' \
"https://api.digitalocean.com/v2/cdn/endpoints/$ENDPOINT_ID"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment