---
- name: Install certbot and RFC2136 plugin
  apt:
    update_cache: true
    name:
      - certbot
      - python3-certbot-dns-rfc2136
    state: present
  register: apt_result
  retries: 3
  until: apt_result is succeeded

- name: Add DNS credentials
  template:
    src: letsencrypt/rfc2136.ini.j2
    dest: "/etc/letsencrypt/rfc2136.{{ item.certname }}.ini"
    mode: 0600
    owner: root
  loop: "{{ certbot }}"

- name: Add dhparam
  template:
    src: "letsencrypt/dhparam.j2"
    dest: "/etc/letsencrypt/dhparam"
    mode: 0600

- name: Create /etc/letsencrypt/conf.d
  file:
    path: /etc/letsencrypt/conf.d
    state: directory
    mode: 0755

- name: Add Certbot configuration
  template:
    src: "letsencrypt/conf.d/certname.ini.j2"
    dest: "/etc/letsencrypt/conf.d/{{ item.certname }}.ini"
    mode: 0644
  loop: "{{ certbot }}"

- name: Run certbot
  command: certbot --non-interactive --config /etc/letsencrypt/conf.d/{{ item.certname }}.ini certonly
  loop: "{{ certbot }}"

- name: Clean old files
  file:
    path: "{{ item }}"
    state: absent
  loop:
    - "/etc/letsencrypt/options-ssl-nginx.conf"
    - "/etc/letsencrypt/ssl-dhparams.pem"
    - "/etc/letsencrypt/rfc2136.ini"