- name: "Check if certificate already exists for {{ domain }}"
  cert_check_exists:
    domain: "{{ domain }}"
    cert_base_path: "{{ certbot_cert_path }}"
  register: cert_check

- name: "receive certificate for {{ domain }}"
  command: >-
    certbot certonly 
    --agree-tos 
    --email {{ users.administrator.email }}
    --non-interactive 
    {% if certbot_acme_challenge_method != "webroot" %}
    --dns-{{ certbot_acme_challenge_method }}
    --dns-{{ certbot_acme_challenge_method }}-credentials {{ certbot_credentials_file }}
    --dns-{{ certbot_acme_challenge_method }}-propagation-seconds {{ certbot_dns_propagation_wait_seconds }}
    {% else %}
    --webroot 
    -w {{ certbot_webroot_path }}
    {% endif %}
    {% if wildcard_domain is defined and ( wildcard_domain | bool ) %}
    -d {{ primary_domain }} 
    -d *.{{ primary_domain }}
    {% else %}
    -d {{ domain }}
    {% endif %}
    {{ '--test-cert' if mode_test | bool else '' }}
  register: certbot_result
  changed_when: "'Certificate not yet due for renewal' not in certbot_result.stdout"
  when: not cert_check.exists