This Task automates the process of obtaining, configuring, and renewing SSL certificates using Let's Encrypt with Ansible. The automation will ensure all web servers have up-to-date SSL certificates, reducing manual work and maintaining a secure environment.
sudo apt update && sudo apt install -y ansible
inventory.yml
) with target servers:all:
hosts:
webserver1:
ansible_host: 192.168.1.10
ansible_user: ubuntu
ansible_ssh_private_key_file: ~/.ssh/id_rsa
Create a playbook ssl_certificate.yml
to:
---
- name: SSL Certificate Management
hosts: all
become: yes
tasks:
- name: Install required packages
apt:
name: ["certbot", "python3-certbot-nginx"]
state: present
update_cache: yes
when: ansible_os_family == "Debian"
- name: Install required packages for RHEL
yum:
name: ["certbot", "python3-certbot-nginx"]
state: present
when: ansible_os_family == "RedHat"
- name: Obtain SSL Certificate using Certbot
command: certbot certonly --nginx --non-interactive --agree-tos --email admin@example.com -d example.com -d www.example.com
args:
creates: /etc/letsencrypt/live/example.com/fullchain.pem
- name: Configure SSL in Nginx
template:
src: templates/nginx_ssl.j2
dest: /etc/nginx/sites-available/example.com
notify: Restart Nginx
- name: Ensure SSL renewal via cron
cron:
name: "Renew Let's Encrypt Certificates"
job: "certbot renew --quiet"
minute: "0"
hour: "0"
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
Execute the playbook to deploy SSL:
ansible-playbook -i inventory.yml ssl_certificate.yml
sudo certbot certificates
sudo certbot renew --dry-run
sudo certbot renew --dry-run
0 0 * * * certbot renew --quiet
sudo systemctl enable certbot.timer
openssl x509 -enddate -noout -in /etc/letsencrypt/live/example.com/fullchain.pem
This project is ready for implementation and can be deployed across any cloud or on-prem infrastructure.