---

- name: nginx install
  apt:
    force_apt_get: true
    install_recommends: false
    name: "{{ nginx_packages }}"
    state: present
  register: apt_status
  retries: 60
  until: apt_status is success or ('Failed to lock apt for exclusive operation' not in apt_status.msg and '/var/lib/dpkg/lock' not in apt_status.msg)

- name: nginx remove default vhost
  notify: restart nginx
  loop:
    - /etc/nginx/sites-enabled/default
    - /etc/nginx/sites-enabled/default.conf
  file:
    path: "{{ item }}"
    state: absent

- name: nginx check old ssl conf exists
  register: nginx_old_ssl_conf
  stat:
    path: /etc/nginx/conf.d/ssl.conf

- name: nginx migrate old ssl certificate conf
  when: nginx_old_ssl_conf.stat.exists
  notify: restart nginx
  loop:
    - grep ssl_certificate /etc/nginx/conf.d/ssl.conf > /etc/nginx/conf.d/ssl_certificate.conf
    - mv /etc/nginx/conf.d/ssl.conf /etc/nginx/conf.d/ssl.conf.old
  command:
    cmd: "{{ item }}"

- name: nginx check ssl cert conf exists
  register: nginx_ssl_cert_conf
  stat:
    path: /etc/nginx/conf.d/ssl_certificate.conf

- name: nginx update ssl certificate conf
  when:
    - nginx_ssl_cert_conf.stat.exists
    - nginx_ssl_certificate != "/etc/ssl/certs/ssl-cert-snakeoil.pem"
  notify: restart nginx
  lineinfile:
    path: /etc/nginx/conf.d/ssl_certificate.conf
    regexp: 'ssl_certificate\s+([\w/\-\_\.]+);'
    line: 'ssl_certificate {{ nginx_ssl_certificate }};'

- name: nginx update ssl certificate key conf
  when:
    - nginx_ssl_cert_conf.stat.exists
    - nginx_ssl_certificate_key != "/etc/ssl/private/ssl-cert-snakeoil.key"
  notify: restart nginx
  lineinfile:
    path: /etc/nginx/conf.d/ssl_certificate.conf
    regexp: 'ssl_certificate_key\s+([\w/\-\_\.]+);'
    line: 'ssl_certificate_key {{ nginx_ssl_certificate_key }};'

...
