Monitoring & Alerting Of SSL Certificate Expiry

The important part of managing infrastructure is to ensure that all our services and applications are monitored and alerting is in place So that we can avoid Downtime.

In my previous articles, I have explained,

How to Setup WordPress site with LEMP Stack

How to Setup free SSL certificate for a domain

Going forward, In this article, We will see how to monitor SSL certificate of each domains which is configured across environments and Services.

AWS Services Used To Monitor SSL Certificate:

  • AWS SNS – Send an alert to custom channels such as Email , Slack , SMS etc.
  • AWS Cloudwatch – cloudwatch events to trigger Lambda functions at scheduled intervals.
  • AWS Lambda – AWS Lambda is a compute service that lets you run code without provisioning or managing servers. AWS Lambda executes your code only when needed and scales automatically.

Setup Services:


First, We need to create a SNS topic and then we have to subscribe to email , SMS or Slack webhook.

To create a SNS topic, Go to SNS Console.

Choose Topics in the left pane, Click Create Topic.

Type the name for the sns topics and then choose Create Topic.

Whenever you create a SNS topic , You will provided a ARN , an endpoint using which you an communicate with other AWS Services.

Now we have to add subscribers such as email , SMS to this SNS topic so that we will be alerted based on the configuration of Lambda function.

To add Subscribers , Choose Create Subscription , You will be asked to choose a subscriber , For instance, I am choosing Email JSON (I will get the alerts in the JSON format) and I will type in my email address and then click create subscription.

If you refresh the page, You will see the subscriber waiting for the confirmation,

I have got a email from the AWS SNS with the confirmation link,

Click the above URL for confirmation, Once done Go back to your SNS topic and refresh the page,

Now We have a SNS topic and a subscriber for alerting.


Let’s go ahead and create a lambda function.

Go to AWS lambda Console,

Choose Create function , Select Author from Scratch

Provide a Name : testfunction

Runtime : Python 2.7

Then We have to create a Execution role with SNS Publish Permission.

Choose , Create a new role from AWS policy templates

Role name : testrole (give name as you need)

Policy templates : Amazon SNS Publish policy

Click , Create function.

We have created a Lambda function , lets go ahead and configure the function.

Set the handler to index.lambda_handler


Copy & paste the below code into the function code section,

import socket
import ssl, boto3
import re,sys,os,datetime

def ssl_expiry_date(domainname):
    ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'
    context = ssl.create_default_context()
    conn = context.wrap_socket(
    # 3 second timeout because Lambda has runtime limitations
    conn.connect((domainname, 443))
    ssl_info = conn.getpeercert()
    return datetime.datetime.strptime(ssl_info['notAfter'], ssl_date_fmt).date()

def ssl_valid_time_remaining(domainname):
    """Number of days left."""
    expires = ssl_expiry_date(domainname)
    return expires - datetime.datetime.utcnow().date()

def sns_Alert(dName, eDays, sslStatus):
    sslStat = dName + ' SSL certificate will be expired in ' + eDays +' days!! '
    snsSub = dName + ' SSL Certificate Expiry ' + sslStatus + ' alert'
    print sslStat
    print snsSub
    response = client.publish(
    Message= sslStat,
    Subject= snsSub
#####Main Section
client = boto3.client('sns')
def lambda_handler(event, context):
    f = ['','','']
    for dName in f:
        expDate = ssl_valid_time_remaining(dName.strip())
        (a, b) = str(expDate).split(',')
        (c, d) = a.split(' ')
    # Critical alerts 
        if int(c) < 15:
            sns_Alert(dName, str(c), 'Critical')
      # Frist critical alert on 20 th day      
        elif int(c) == 10:
            sns_Alert(dName, str(c), 'Critical')
    #second warning alert on 40th day
        elif int(c) == 15:
            sns_Alert(dName, str(c), 'Warning')
    #First warning alert on 50th day      
        elif int(c) == 20:
            sns_Alert(dName, str(c), 'Warning')
            print('Everything Fine..')

Now we have to add the domain names and the alerting days based on Warning and Critical.Also you can monitor multiple domains followed by ‘,’.

Example : [‘’,’’,’’]

Update the TargetArn with our SNS topic ARN.

We have configured the script to send us a Warning on 20th day and 15th day and a Critical alert on 10th day.

Once everything is configured, Click Save.

Cloudwatch Event:

now we need to create a cloudwatch event to trigger the lambda function at the scheduled intervals.

Go to AWS Cloudwatch Console,

Choose Events –> Rules

Click Create Rule,

Choose Event Source as Scheduled,provide a cron expression as per your requirement, It’s good to check everyday.

In Targets,Choose the lambda function ,Click Configure details

provide a name to the Rule and Click create rule.

Now that We have Cloudwatch event to trigger lambda function and publish to SNS topic which will alert us based on Warnings and Criticial days configured.

Confirming Alerting:

You can manually test the setup ,By changing the warning and critical days to the current expiry date in the lambda function.

If your certificate is about to expire in 30 days, Then set the Warning as 30 days and critical as 25 days.

Lets configure a test event, To do this, Go to the Lambda function,

Choose configure test events, give a name to it and click Create

Now Click Test, If you have configured everything correctly You should get an email will the message as shown below:

"Type" : "Notification",
"MessageId" : "aae9169a-4bf0-595d-8524-4019f0eb09a6",
"TopicArn" : "arn:aws:sns:ap-southeast-1:609249146283:sslcertificateexpirymonitor",
"Subject" : " SSL Certificate Expiry Warning alert",
"Message" : " SSL certificate will be expired in 30 days!! ",

Hope you have learnt how to monitor SSL certificate and alerting for the same.

If you have liked it , Check out my other articles.