Created
July 24, 2020 16:21
-
-
Save ronaldgrn/f1a99fde2f380c7d94233466aa88d8fd to your computer and use it in GitHub Desktop.
lua-resty-auto-ssl: Delete expired (or near expired) certs from redis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import redis | |
import json | |
from datetime import datetime, timedelta | |
from redis.exceptions import ResponseError | |
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True) | |
now = datetime.now() | |
three_days_from_now = now + timedelta(days=3) | |
keys_to_purge = [] | |
flagged_key_count = 0 | |
valid_key_count = 0 | |
print("") | |
print("======== %s ========" % now.strftime('%m/%d/%Y, %H:%M:%S')) | |
for key in r.scan_iter(): | |
try: | |
cert_data = r.get(key) | |
cert_dict = json.loads(cert_data) | |
expiry = cert_dict.get('expiry', None) | |
if expiry: | |
key_expires_on = datetime.fromtimestamp(expiry) | |
# Sanity check in case the 'expiry' format changes in the future | |
# Validates timestamp between 2017 - 2030 | |
if expiry < 1500000000 or expiry > 1900000000: | |
raise Exception("Invalid Timestamp Detected. Aborting") | |
if key_expires_on < three_days_from_now: | |
print("Key %s is expiring within 3 days. Adding to purge list" % key) | |
keys_to_purge.append(key) | |
flagged_key_count += 1 | |
else: | |
valid_key_count += 1 | |
except ResponseError: | |
# Wrong datatype - skip | |
# print("Invalid datatype for key ", key) | |
continue | |
except json.decoder.JSONDecodeError: | |
print("Warn: Unable to decode %s. Possibly a challenge key." % key) | |
except Exception as e: | |
print("Failed on Key %s" % key) | |
raise e | |
print("Flagged Key Count:", flagged_key_count) | |
print("Valid Key Count:", valid_key_count) | |
# Purge keys marked to purge, but first, more validation | |
if len(keys_to_purge) > 25: | |
raise Exception("Too many keys (%s) will be purged with this operation. Aborting." % len(keys_to_purge)) | |
else: | |
# Purge Keys | |
for key in keys_to_purge: | |
print("Deleting", key) | |
r.delete(key) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment