Automate LetsEncrypt SSL Installation with Ansible for multiple domains

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

https://devops4solutions.com/

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

Prerequisite:

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

Steps:

  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
certbot_create_standalone_stop_services:
- nginx
apache_vhosts:
- {servername: "abcyourdomain.com", documentroot: "/var/www/abcyourdomain.com"}
- {servername: "abcyourdomain1.com", documentroot: "/var/www/abcyourdomain1.com"}

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
apt_repository:
repo: 'ppa:certbot/certbot'
- name: Install Certbot's Nginx package
apt:
name: python-certbot-nginx
state: present

- name: Check if certificate already exists.
stat:
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.
service:
name: "{{ item }}"
state: stopped
with_items:
- "{{ 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.
service:
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
vars_files:
- environments/{{ env }}//group_vars//main.yml
roles:
- 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