pip certbotのインストールとcron用更新スクリプト
certbot 起動するたびに /var/log/letsencrypt/letsencrypt.log を生産していくので
check_cert.sh で保存して更新期限まで何日あるか直接ファイルを見て、30日以内なら
certbot renew するスクリプトを gemini に作ってもらいました
/etc/letsencrypt/renewal/*.conf
を見ているので、存在するドメイン設定だけぐるぐる回ります
#!/bin/bash
# --- 設定項目 ---
DEBUG=1 # 1:詳細表示 / 0:実行時のみ表示
THRESHOLD_DAYS=30 # 残り何日を切ったら実行するか
EXEC_PRG="/usr/bin/certbot renew"
#EXEC_PRG='scl enable rh-python36 "/opt/certbot/bin/certbot renew"'
#EXEC_PRG='scl enable rh-python38 "/opt/certbot/bin/certbot renew"'
RENEWAL_DIR="/etc/letsencrypt/renewal"
# ----------------
[ "$DEBUG" -eq 1 ] && echo "--- Certificate Check Start (Threshold: $THRESHOLD_DAYS days) ---"
for conf in "$RENEWAL_DIR"/*.conf; do
# 設定ファイルが存在しない場合はスキップ
[ -e "$conf" ] || continue
DOMAIN=$(basename "$conf" .conf)
# 対応するディレクトリの最新 pem ファイルを取得
LATEST_PEM=$(ls -t /etc/letsencrypt/archive/"$DOMAIN"/fullchain*.pem 2>/dev/null | head -n 1)
if [ -z "$LATEST_PEM" ]; then
[ "$DEBUG" -eq 1 ] && echo "[$DOMAIN] Error: No .pem file found in archive."
continue
fi
# ファイルの更新日から経過日数と残り日数を計算
# (現在時刻 - ファイル更新時刻) / 86400秒
DIFF_DAYS=$(( ($(date +%s) - $(stat -c %Y "$LATEST_PEM")) / 86400 ))
REMAINING_DAYS=$(( 90 - DIFF_DAYS ))
# 判定と実行
if [ "$REMAINING_DAYS" -lt "$THRESHOLD_DAYS" ]; then
echo "[ACTION] $DOMAIN (Remaining: $REMAINING_DAYS days)"
# 指定されたコマンドにドメイン名を添えて実行
$EXEC_PRG --cert-name "$DOMAIN"
else
# デバッグモード時のみスキップ情報を表示
[ "$DEBUG" -eq 1 ] && echo "[SKIP] $DOMAIN (Remaining: $REMAINING_DAYS days)"
fi
done
[ "$DEBUG" -eq 1 ] && echo "--- Check Finished ---"
・cronに登録するならこんな感じ日曜 3:03 に実行されます
3 3 * * 0 /root/check_cert.sh
・pip certbot install CentOS 7の場合 rh-python38
# yum install rh-python38 --enablerepo=centos-sclo-rh
# scl enable rh-python38 bash
# python3.8 -m venv /opt/certbot/
# /opt/certbot/bin/pip install --upgrade pip
# /opt/certbot/bin/pip install certbot
# /opt/certbot/bin/pip install urllib3==1.26.6
# /opt/certbot/bin/certbot --version
3.0.1
・pip certbot install CentOS 6の場合 rh-python36
# yum install centos-release-scl-rh
# vi /etc/yum.repos.d/CentOS-SCLo-scl-rh.repo
baseurl=http://ftp.iij.ad.jp/pub/linux/centos-vault/centos/6.9/sclo/$basearch/rh/
enabled=0
# yum install rh-python36 --enablerepo=centos-sclo-rh
# scl enable rh-python36 bash
# python -m venv /opt/certbot/
# /opt/certbot/bin/pip install --upgrade pip
# /opt/certbot/bin/pip install certbot cryptography==3.4.1
# /opt/certbot/bin/certbot --version
certbot 1.23.0
pip なら
certbot-nginx
certbot-apache
とかのプラグインも簡単に入る
certbot-dns-cloudflare
certbot-dns-sakuracloud
dnsプラグインでワイルドカード証明書も簡単
詳しくは公式を
https://github.com/certbot/certbot
※最近は timer 設定するので cron を使うのはレア
書く場所が微妙にいろいろ違うのがややこしい
Redhat系 CentOS7 AmazonLinux2 Rocky alma
/usr/lib/systemd/system/certbot-renew.timer
/etc/sysconfig/certbot
# systemctl enable certbot-renew.timer# systemctl start certbot-renew.timer
Ubuntu系
/usr/lib/systemd/system/certbot.timer
/usr/lib/systemd/system/certbot.service
勝手に動いていていらなかった気もする# systemctl enable certbot.timer
# systemctl start certbot.timer
