這方法最新版本測試失敗,請參考:https://github.com/eclipse/mosquitto/blob/master/README-letsencrypt.md
翻譯如下
在類Unix操作系統上,Mosquitto在載入配置文件後但在激活任何配置之前,將嘗試放棄root訪問權限。這意味著,如果您使用的是Let's Encrypt TLS證書,它將無法訪問通常位於 /etc/letsencrypt/live/ 目錄中的證書和私鑰。
為了解決這個問題,在 misc/letsencrypt/mosquitto-copy.sh 中提供了一個示例的部署更新鉤子腳本,該腳本顯示了如何將 Mosquitto Broker 的證書和私鑰複製到 /etc/mosquitto/certs/ 目錄中,並設置正確的所有權和權限,以便 Broker 可以訪問這些證書,但其他用戶則不能。然後,它會通知 Mosquitto 重新載入這些證書。
使用此腳本可以讓您在不需要給予 Mosquitto root 訪問權限的情況下,愉快地使用 Let's Encrypt 證書,而且無需重新啟動 Mosquitto。
misc/letsencrypt/mosquitto-copy.sh
※ 來源:https://github.com/eclipse/mosquitto/blob/master/misc/letsencrypt/mosquitto-copy.sh
#!/bin/sh
# This is an example deploy renewal hook for certbot that copies newly updated
# certificates to the Mosquitto certificates directory and sets the ownership
# and permissions so only the mosquitto user can access them, then signals
# Mosquitto to reload certificates.
# RENEWED_DOMAINS will match the domains being renewed for that certificate, so
# may be just "example.com", or multiple domains "www.example.com example.com"
# depending on your certificate.
# Place this script in /etc/letsencrypt/renewal-hooks/deploy/ and make it
# executable after editing it to your needs.
# Set which domain this script will be run for
MY_DOMAIN=example.com
# Set the directory that the certificates will be copied to.
CERTIFICATE_DIR=/etc/mosquitto/certs
for D in ${RENEWED_DOMAINS}; do
if [ "${D}" = "${MY_DOMAIN}" ]; then
# Copy new certificate to Mosquitto directory
cp ${RENEWED_LINEAGE}/fullchain.pem ${CERTIFICATE_DIR}/server.pem
cp ${RENEWED_LINEAGE}/privkey.pem ${CERTIFICATE_DIR}/server.key
# Set ownership to Mosquitto
chown mosquitto: ${CERTIFICATE_DIR}/server.pem ${CERTIFICATE_DIR}/server.key
# Ensure permissions are restrictive
chmod 0600 ${CERTIFICATE_DIR}/server.pem ${CERTIFICATE_DIR}/server.key
# Tell Mosquitto to reload certificates and configuration
pkill -HUP -x mosquitto
fi
done
這是一個用於 Certbot 的示例部署更新鉤子腳本,它會將新更新的證書複製到 Mosquitto 證書目錄中,並設置所有權和權限,以便只有 mosquitto 使用者可以訪問,然後通知 Mosquitto 重新載入證書。
您可以將這個腳本放置在 /etc/letsencrypt/renewal-hooks/deploy/ 目錄中,並在編輯腳本以滿足您的需求後,使其可執行。
請設置您希望運行此腳本的域名:
MY_DOMAIN=example.com
設置證書將被複製到的目錄:
CERTIFICATE_DIR=/etc/mosquitto/certs
接下來的部分迴圈將檢查更新的域名,如果與您的域名相符,則會執行以下操作:
將新的完整鏈證書複製到 Mosquitto 目錄:
cp ${RENEWED_LINEAGE}/fullchain.pem ${CERTIFICATE_DIR}/server.pem
將新的私鑰複製到 Mosquitto 目錄:
cp ${RENEWED_LINEAGE}/privkey.pem ${CERTIFICATE_DIR}/server.key
將擁有權設置為 mosquitto 使用者:
chown mosquitto: ${CERTIFICATE_DIR}/server.pem ${CERTIFICATE_DIR}/server.key
確保許可權受到限制:
chmod 0600 ${CERTIFICATE_DIR}/server.pem ${CERTIFICATE_DIR}/server.key
通知 Mosquitto 重新載入證書和配置:
pkill -HUP -x mosquitto
這樣,您就可以使用這個腳本,讓 Mosquitto 與 Let's Encrypt 證書一起運作,而無需給予 Mosquitto root 訪問權限,也不需要重新啟動 Mosquitto。記得根據您的需求編輯腳本中的域名和目錄路徑。