main.yml (3040B)
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 changed_when: false 14 check_mode: false 15 ignore_errors: true 16 17 - name: Fail if nginx misconfigured 18 ansible.builtin.fail: 19 msg: The nginx configuration is broken. You need to have a valid nginx configuration before certs can be issued. 20 when: result is failed 21 22 - name: Check if domains have changed 23 block: 24 - name: Register certificate domains 25 ansible.builtin.command: 26 argv: 27 - certbot 28 - certificates 29 - --cert-name 30 - "{{ cert_name }}" 31 changed_when: false 32 check_mode: false 33 failed_when: false 34 register: cert_domains_dirty 35 36 - name: Cleanup domain list 37 set_fact: 38 actual_cert_domains: >- 39 {{ 40 cert_domains_dirty.stdout 41 | regex_findall('(?m)^\s*Domains:\s*(.*)$') 42 | join(' ') 43 | split(' ') 44 | map('trim') 45 | select('!=', '') 46 | list 47 | sort 48 }} 49 50 - name: Determine if domains have changed 51 set_fact: 52 cert_domains_changed: "{{ actual_cert_domains != (wanted_cert_domains | map('trim') | select('!=', '') | list | sort) }}" 53 54 - name: Disable site in nginx if cert needs to be created 55 when: cert_domains_changed 56 ansible.builtin.file: 57 path: "/etc/nginx/sites-enabled/{{ item }}" 58 state: absent 59 with_items: "{{ nginx_sites | list }}" 60 notify: Restart nginx 61 62 # We need to make sure that our handler notifies nginx to restart NOW 63 - name: Flush handlers 64 meta: flush_handlers 65 66 - name: Create or update certs 67 command: 68 argv: "{{ cmd + domain_args | list }}" 69 register: certbot_result 70 # certbot is run on every deploy but only does something when the cert is 71 # missing or close to expiry; in the common case it just says so and exits 0. 72 # Anything we do not recognize as that no-op counts as a change, so nginx 73 # still gets reloaded if certbot ever words its output differently. 74 changed_when: "'not yet due for renewal' not in certbot_result.stdout" 75 notify: Restart nginx 76 vars: 77 cmd: 78 - certbot 79 - -v 80 - certonly 81 - --cert-name 82 - "{{ cert_name }}" 83 - --nginx 84 - --keep-until-expiring 85 - --noninteractive 86 - --agree-tos 87 - --email 88 - admin@{{ domain_name }} 89 domain_args: "{{ wanted_cert_domains | product(['-d']) | map('reverse') | flatten | list }}" 90 91 - name: Enable nginx sites 92 ansible.builtin.file: 93 src: /etc/nginx/sites-available/{{ item }} 94 dest: /etc/nginx/sites-enabled/{{ item }} 95 state: link 96 force: true 97 notify: Restart nginx 98 with_items: "{{ nginx_sites | list }}"