Automating SSL Certificate Renewal with Certbot and Google Cloud DNS |

Automating SSL Certificate Renewal with Certbot and Google Cloud DNS

Posted on Dec 18, 2024

Prerequisites

  • A domain managed by Google Cloud DNS
  • A Linux server (Ubuntu/Debian)
  • Root/sudo access
  • Google Cloud project with billing enabled

Installation Steps

First, install the required Certbot DNS plugin:

pip install certbot-dns-google
sudo apt-get update
sudo apt-get install python3-certbot-dns-google

Google Cloud SDK Setup

Install the Google Cloud SDK:

curl -O https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-cli-linux-x86_64.tar.gz
tar -xf google-cloud-cli-linux-x86_64.tar.gz
./google-cloud-sdk/install.sh

Service Account Configuration

Create and configure a service account for Certbot:

gcloud iam service-accounts create certbot-UNIQUE_IDENTIFIER \
    --display-name "Certbot Service Account UNIQUE_IDENTIFIER"
gcloud projects add-iam-policy-binding YOUR_PROJECT_ID \
    --member="serviceAccount:certbot-UNIQUE_IDENTIFIER@YOUR_PROJECT_ID.iam.gserviceaccount.com" \
    --role="roles/dns.admin"
gcloud iam service-accounts keys create credentials.json \
    --iam-account=certbot-UNIQUE_IDENTIFIER@YOUR_PROJECT_ID.iam.gserviceaccount.com

Certificate Renewal Script

Create a renewal script (renew-ssl.sh):

#!/bin/bash
sudo certbot certonly \
  --dns-google \
  --dns-google-credentials /home/kn/autorenew/credentials.json \
  -d domain.com \
  -d *.domain.com \
  --preferred-challenges dns-01 \
  --agree-tos \
  --non-interactive \
  --expand

# Reload nginx after renewal
sudo systemctl reload nginx
sudo systemctl restart nginx
sudo systemctl reload nginx
sudo rm -rf /var/cache/nginx/*
sudo systemctl reload nginx
sudo systemctl restart nginx
sudo systemctl reload nginx

Automation

Add to crontab to run twice daily:

0 0,12 * * * /path/to/renew-ssl.sh

Remember to:

  • Replace YOUR_PROJECT_ID with your actual Google Cloud project ID
  • Ensure the credentials.json path matches your system
  • Make the renewal script executable using chmod +x /path/to/renew-ssl.sh
  • Test the script manually before setting up the cron job