main.yml (2276B)
1 --- 2 # Create certs with certbot and the nginx plugin. 3 # Required vars: 4 # - domain_name: send e-mails to admin@{{ domain_name }} 5 # - cert_name: name of the certbot certificate 6 # - wanted_cert_domains: list of domains to issue a cert for 7 # - nginx_sites: nginx sites that use this domain, enabled when 8 # cert creation succeeds 9 10 - name: Check nginx config 11 ansible.builtin.command: nginx -c /etc/nginx/nginx.conf -t 12 register: result 13 ignore_errors: true 14 15 - name: Fail if nginx misconfigured 16 ansible.builtin.fail: 17 msg: The nginx configuration is broken. You need to have a valid nginx configuration before certs can be issued. 18 when: result is failed 19 20 - name: Check if domains have changed 21 block: 22 - name: Register certificate domains 23 shell: "certbot certificates --cert-name {{ cert_name }} | grep Domains | cut -d':' -f2" 24 changed_when: false 25 register: cert_domains_dirty 26 27 - name: Cleanup domain list 28 set_fact: 29 actual_cert_domains: "{{ cert_domains_dirty.stdout | trim | split(' ') | map('trim') | select('!=', '') | list | sort }}" 30 31 - name: Determine if domains have changed 32 set_fact: 33 cert_domains_changed: "{{ actual_cert_domains != (wanted_cert_domains | map('trim') | select('!=', '') | list | sort) }}" 34 35 - name: Disable site in nginx if cert needs to be created 36 when: cert_domains_changed 37 ansible.builtin.file: 38 path: "/etc/nginx/sites-enabled/{{ item }}" 39 state: absent 40 with_items: "{{ nginx_sites | list }}" 41 notify: Restart nginx 42 43 # We need to make sure that our handler notifies nginx to restart NOW 44 - name: Flush handlers 45 meta: flush_handlers 46 47 - name: Create or update certs 48 command: 49 argv: "{{ cmd + domain_args | list }}" 50 vars: 51 cmd: 52 - certbot 53 - -v 54 - certonly 55 - --cert-name 56 - "{{ cert_name }}" 57 - --nginx 58 - --keep-until-expiring 59 - --noninteractive 60 - --agree-tos 61 - --email 62 - admin@{{ domain_name }} 63 domain_args: "{{ wanted_cert_domains | product(['-d']) | map('reverse') | flatten | list }}" 64 65 - name: Enable nginx sites 66 file: 67 src: /etc/nginx/sites-available/{{ item }} 68 dest: /etc/nginx/sites-enabled/{{ item }} 69 state: link 70 notify: Restart nginx 71 with_items: "{{ nginx_sites | list }}"