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