Skip to content

Instantly share code, notes, and snippets.

@usrflo
Last active April 24, 2024 13:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save usrflo/fc979e02504c4e3345c3e6a731c96028 to your computer and use it in GitHub Desktop.
Save usrflo/fc979e02504c4e3345c3e6a731c96028 to your computer and use it in GitHub Desktop.
Remove outdated letsencrypt CSRs, keys and certificates from /etc/letsencrypt
#!/bin/bash
# Remove outdated letsencrypt CSRs, keys and certificates
lesslBasePath=/etc/letsencrypt
keepOldVersions=1
keepOldCsrDays=180
keepOldKeysDays=180
if [ ! -d "$lesslBasePath" ]; then
echo "Error: configured Let's Encrypt base path $lesslBasePath does not exist" >&2
exit 1
fi
# cleanup csr directory
if [ -d "$lesslBasePath/csr" ]; then
find $lesslBasePath/csr -name *_csr-certbot.pem -type f -mtime +$keepOldCsrDays -exec rm -f {} ';'
fi
# cleanup keys directory
if [ -d "$lesslBasePath/keys" ]; then
find $lesslBasePath/keys -name *_key-certbot.pem -type f -mtime +$keepOldKeysDays -exec rm -f {} ';'
fi
function getFileId() {
local result=`expr "$1" : '.*[privkey|cert|chain|fullchain]\(.[0-9]*\).pem$'`
if [ -n "$result" ] && [ "$result" -eq "$result" ] 2>/dev/null; then
return $result
fi
# not a number
return -1
}
# cleanup archive directory
if [ -d "$lesslBasePath/live" ]; then
for symlink in $lesslBasePath/live/*/privkey.pem; do
target=`readlink -f $symlink`
if [ $? -ne 0 ]; then
continue
fi
getFileId "$target"
liveId=$?
if [ $liveId -eq -1 ]; then
continue
fi
cmpId=$( expr $liveId - $keepOldVersions )
for archivefile in $(dirname $target)/*.pem; do
getFileId "$archivefile"
archiveId=$?
if [ $archiveId -eq -1 ]; then
continue
fi
if [ "$archiveId" -lt "$cmpId" ]; then
rm "$archivefile"
fi
done
done
fi
@alsoeric
Copy link

this script delete essential files: nginx.conf options-ssl-nginx.conf ssl-dhparams.pem based on what found so far. I was able to recover them but a bit of a heart stoppper

@usrflo
Copy link
Author

usrflo commented Sep 18, 2023

@alsoeric : this script only deletes files symlinked via $lesslBasePath/live/*/privkey.pem that suffice the following filename pattern: expr "$1" : '.*[privkey|cert|chain|fullchain]\(.[0-9]*\).pem$'.

So something else must have deleted nginx.conf options-ssl-nginx.conf ssl-dhparams.pem in your case.

@attinderdhillon
Copy link

getting error -

certbot-cleanup.sh: 25: Syntax error: "(" unexpected

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment