fbpx

Letsencrypt and webservices auto-restart

So I have a bunch of SSL-certificates, wildcarded, that is renewing from time to time. And since I hate googing for things ending up without any results anyway, I recently wrote a script that is checking against apache and nginx pid-files if any pem-files in the letsencrypt directory (under /etc/letsencrypt) are newer than the last restart time of the webserver.

If the pid files for apache and nginx are older than the respective pem-file, the script is set to restart the webserver. The script itself has focus on apache, since I still have unmigrated services left in my systems. The below script has been set to email me on such changes, but has been removed from this snippet.

#!/bin/bash

apachePid=/var/run/apache2/apache2.pid
nginxPid=/var/run/nginx.pid

ap=$(which apachectl)
allowSslScan=0
apacheDate=""
if [ -f $apachePid ] ; then
	allowSslScan=1
	apacheDate=$(date -r ${apachePid} "+%s")
	restartCmd="$ap restart"
fi

if [ -f $nginxPid ] ; then
	nginxDate=$(date -r ${nginxPid} "+%s")
	allowSslScan=1
	if [ "" != "$apacheDate" ] ; then
		if [ $nginxDate -gt $apacheDate ] ; then
			echo "Nginx date is newer than apache, will use that instead."
			apacheDate=$nginxDate
		fi
	else
		apacheDate=$nginxDate
	fi
	restartCmd="service nginx restart"
fi

if [ "$allowSslScan" = "1" ] ; then
	requireRestart=0

	if [ -d /etc/letsencrypt/live ] ; then
		pems=$(find /etc/letsencrypt/live -type l)
		for pem in $pems
		do
			realfile=$(readlink -f $pem)
			thisDate=$(date -r $realfile "+%s")
			if [ $thisDate -gt $apacheDate ] ; then
				requireRestart=1
			fi
		done
	fi
	if [ "$requireRestart" = "1" ] ; then
		echo "Chosen restart command: $restartCmd"
		echo "One or more SSL certificates are newer than the current apache2 session. We require a restart!"
		$restartCmd
	fi
fi

Upptäck mer från Tornevall

Prenumerera för att få de senaste inläggen skickade till din e-post.

You may also like