Hello Guys,
I was working on a use case where i need to write a playbook if the SSL cert is expiring in nexy 30 days.I should get a email alert that the ssl cert for the site will expire and reminding me to renew the same.
So i have wrote a playbook and schedule to execute it every week So i keep on getting reminders that i need to renew the ssl cert. the playbook looks like this
---
- name: check the certs for site
hosts: localhost
# connection: local
vars:
worn: 30
user_email: vijay9867206455@gmail.com
site_url: www.google.com
tasks:
- name: Get a cert from an https port
community.crypto.get_certificate:
host: "{{ site_url }}"
port: 443
delegate_to: localhost
register: cert
- name: How many days until cert expires
ansible.builtin.debug:
msg: "cert expires in: {{ expire_days }} days."
when: expire_days | int <= "{{ worn }}"| int
vars:
expire_days: "{{ (( cert.not_after | to_datetime('%Y%m%d%H%M%SZ')) - (ansible_date_time.iso8601 | to_datetime('%Y-%m-%dT%H:%M:%SZ')) ).days }}"
- name: Include Jinja template for email body
template:
src: alert_email.html.j2
dest: /tmp/alert_email.html
vars:
expire_days: "{{ (( cert.not_after | to_datetime('%Y%m%d%H%M%SZ')) - (ansible_date_time.iso8601 | to_datetime('%Y-%m-%dT%H:%M:%SZ')) ).days }}"
when: expire_days | int <= "{{ worn }}"| int
- name: Send email Alert
mail:
host: smtp.gmail.com
port: 587
subtype: html
to:
- "vijay9867206455@gmail.com"
subject: "Alert: cert is failing on"
subtype: html
body: "{{ lookup('file', '/tmp/alert_email.html') }}"
username:
password:
when: expire_days | int <= "{{ worn }}"
vars:
expire_days: "{{ (( cert.not_after | to_datetime('%Y%m%d%H%M%SZ')) - (ansible_date_time.iso8601 | to_datetime('%Y-%m-%dT%H:%M:%SZ')) ).days }}"
when: expire_days | int <= "{{ worn }}"| int
replace the email id with your own email id and also update the username and password for the email and you write a nice email template for it and that should be it.