Create SSL Nginx with Ansible

Dec 14, 2022 min read

multiple way

This is maybe one of the longest notes in this notes. Here we go….

First before I meet this ansible roles, when I want to deploy domain name with nginx server. I only install and deploy ssl to manage HTTPS certbot with manually installation which is use standard command line. This is very repetitive and there will be chances human error.

requirements:

  • nginx
  • ansible-playbook
  • ssh connection

So when I feel I can be better than it, I decide to use ansible to create repetitive task. And after the long way I create this ansible roles:

Step 1

I assume that you have knowledge about ansible playbook, basically ansible playbook need roles and host to apply.

first you must create main.yml on roles folder.

- name: Install certbot
  package: 
    update_cache: yes 
    name: 
      - certbot
      - python3-certbot-nginx
    state: latest

- name: Copy file config nginx-domain.conf to target directory
  template:
    src: files/nginx-domain.conf
    dest: "/etc/nginx/sites-available/{{ nginx_domain_name }}"

- name: Check folder exist
  stat: path=/etc/nginx/sites-enabled/{{ nginx_domain_name }}
  register: stat_result

- name: Unlinking file config if exist sites-enabled
  when: stat_result.stat.exists
  shell:
     cmd: unlink /etc/nginx/sites-enabled/{{ nginx_domain_name }}

- name: Linking file config nginx config into sites-enabled
  shell:
     cmd: ln -s /etc/nginx/sites-available/{{ nginx_domain_name }} /etc/nginx/sites-enabled/

- name: restart nginx
  shell:
     cmd: service nginx restart

- name: Generate new certificate if one doesn't exist.
  shell: "certbot --nginx --noninteractive --agree-tos --email {{ certbot_email }} -d {{ nginx_domain_name }}"

- name: restart nginx
  shell:
     cmd: service nginx reload

Description:

  • in the main.yml above run to install certbot and then copy template nginx-domain.conf
  • copy nginx-domain.conf to config nginx directory
  • generate new certificate whit certbot command

nginx-domain.conf template

server {
   server_name {{ nginx_domain_name }};
   access_log /var/log/nginx/{{ nginx_domain_name }}-acc.log;
   error_log /var/log/nginx/{{ nginx_domain_name }}-err.log;
   listen 80;
   root {{ nginx_root_path }};

   location / {
 		try_files $uri $uri/ =404;
    }

}

I put variable nginx_domain_name and nginx_root_path on folder group_vars with domain-nginx filename.