- name: 'Build arguments for letsencrypt acme.sh driver for: {{ cert.key }}'
  set_fact:
    # NOTE(ianw): note the domains are passed in one string (between
    # ") as it makes argument parsing a little easier in the driver.sh
    acme_args: '"{% for domain in cert.value %}-d {{ domain.split(":")[0] }} {% endfor %}"'

- name: Run acme.sh driver for certificate issue
  shell:
    cmd: |
      /opt/acme.sh/driver.sh {{ 'issue-selfsign' if letsencrypt_self_generate_tokens else 'issue' }} {{ acme_args }}
  args:
    chdir: /opt/acme.sh/
  register: acme_output
  environment:
    LETSENCRYPT_STAGING: '{{ "1" if letsencrypt_use_staging else "0" }}'

# NOTE(ianw): The output of the driver is
#
#  challenge-domain:TXT-key
#
# We don't care about the challenge-domain part (we have set all
# _acme-challenge.hostname.o.o records as CNAMES to acme.opendev.org).
# Record the config key along with the TXT record; later we use it to
# check which config keys have been updated and need a refresh.
#
- set_fact:
    acme_txt_required: '{{ acme_txt_required + [(cert.key, item.split(":")[1])] }}'
  loop: '{{ acme_output.stdout_lines }}'