Automate LetsEncrypt SSL Installation with Ansible for multiple domains

Please visit my website and subscribe to my youtube channel for more articles

In this blog, we will Automate LetsEncrypt SSL Installation with Ansible for multiple domains.


  1. Nginx Server . It could be apache or any other server as per your requirement
  2. Ansible Setup


  1. Create a variable file which stores all the variables which are required to run an ansible playbook
# Variables for Role Certbot certs.
certbot_create_if_missing: false
certbot_create_method: standalone
certbot_admin_email: youremailid
- nginx
- {servername: "", documentroot: "/var/www/"}
- {servername: "", documentroot: "/var/www/"}

2. Create a main.yml file that will execute the command of installing certbot. This script handles multiple domains using loop concept in ansible. I have used with_items that will work as a for loop and then based on the result of the first statement it will generate the certificate if not exist

- name: Upgrade System
apt: upgrade=dist update_cache=yes
- name: Add certbot repository
repo: 'ppa:certbot/certbot'
- name: Install Certbot's Nginx package
name: python-certbot-nginx
state: present

- name: Check if certificate already exists.
path: /etc/letsencrypt/live/{{ item.servername}}/cert.pem
register: letsencrypt_cert
with_items: "{{ apache_vhosts }}"
- name: Stop services to allow certbot to generate a cert.
name: "{{ item }}"
state: stopped
- "{{ certbot_create_standalone_stop_services }}"
- name: Generate new certificate if one doesn't exist.
shell: "certbot certonly --standalone --noninteractive --agree-tos --email {{ certbot_admin_email }} -d {{ item.item.servername}}"
with_items: "{{ letsencrypt_cert.results }}"
when: item.stat.exists == False
- name: Start services after cert has been generated.
name: "{{ item }}"
state: started
with_items: "{{ certbot_create_standalone_stop_services }}"

3. Create a main.yml that will call the above file.

- hosts: proxy
become: yes
gather_facts: no
- environments/{{ env }}//group_vars//main.yml
- certbot

4. Now run the playbook

ansible-playbook main.yml -i environments/dev/inventory/hosts — extra-vars env=dev

Written by

Devops Automation Enginneer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store