---
# tasks to enable letsencrypt on Ubuntu
#
# This role expects that you run `nginx` as webserver.
# This role works on Ubuntu machines.
# This role expects the following vars to be set:
# - `letsencrypt_email`  Email address of cert manager
# - `letsencrypt_domains` List of domains to maintain
#                         comma-separated, no blanks
# - `letsencrypt_expand_domains` - true or false
#                         if true, new domains are added
#                         to the already existing list of
#                         certs
#
- name: "enable letsencrypt PPA"
  become: yes
  apt_repository:
      repo: 'ppa:certbot/certbot'
      state: present
  notify: update package cache

- name: "install certbot"
  become: yes
  apt:
      name: certbot
      state: present

- name: "register account"
  become: yes
  command: certbot register -m "{{ letsencrypt_email }}" --non-interactive --agree-tos -vv
  args:
    creates: '/etc/letsencrypt/accounts/acme-v01.api.letsencrypt.org/directory/*/private_key.json'

# For first time creation of certs. Later on use the below task or renewal
- name: "create initial certs"
  become: yes
  command: certbot certonly --standalone --non-interactive -d "{{ letsencrypt_domains }}" --pre-hook "sudo service nginx stop" --post-hook "sudo service nginx start" -m "{{ letsencrypt_email }}" --agree-tos --rsa-key-size 4096
  args:
    creates: '/etc/letsencrypt/live/*/cert.pem'

# in case additional domains must be added to the already existing ones
- name: "create certs (expand list of domains)"
  become: yes
  command: certbot certonly --standalone --non-interactive -d "{{ letsencrypt_domains }}" --pre-hook "sudo service nginx stop" --post-hook "sudo service nginx start" -m "{{ letsencrypt_email }}" --agree-tos --expand --rsa-key-size 4096
  when: letsencrypt_expand_domains

# Cron task for renewal is installed automatically by the Ubuntu package
