Ansible renew letsencrypt nginx certificates

From snippet wiki
Jump to navigation Jump to search

Even if certbot could renew by itself, you might want to centralize the triggering. Create a host group certbot_nginx and run this script daily.

---
- hosts: certbot_nginx
  vars:
    statefile: /tmp/didrenew
  tasks:

  - name: Cleanup state flag file first
    command: "rm {{ statefile }}"
    args:
      removes: "{{ statefile }}"

  - name: Renew existing certificates
    command: "certbot renew --nginx --post-hook 'touch {{ statefile }}'"
    args:
      creates: "{{ statefile }}"

  - name: Restart nginx, if flag file found
    command: "systemctl restart nginx.service"
    args:
      removes: "{{ statefile }}"

  - name: Cleanup state flag file at last
    command: "rm {{ statefile }}"
    args:
      removes: "{{ statefile }}"