---
- name: Destroy
  hosts: localhost
  connection: local
  gather_facts: false
  no_log: "{{ not (lookup('env', 'MOLECULE_DEBUG') | bool or molecule_yml.provisioner.log|default(false) | bool) }}"
  tasks:
    - block:
        - name: Populate instance config
          set_fact:
            instance_conf: "{{ lookup('file', molecule_instance_config) | molecule_from_yaml }}"
            skip_instances: false
      rescue:
        - name: Populate instance config when file missing
          set_fact:
            instance_conf: {}
            skip_instances: true

    - name: Destroy molecule instance(s)
      ec2:
        state: absent
        instance_ids: "{{ item.instance_ids }}"
      register: server
      with_items: "{{ instance_conf }}"
      when: not skip_instances
      async: 7200
      poll: 0

    - name: Wait for instance(s) deletion to complete
      async_status:
        jid: "{{ item.ansible_job_id }}"
      register: ec2_jobs
      until: ec2_jobs.finished
      retries: 300
      with_items: "{{ server.results }}"

    # Mandatory configuration for Molecule to function.

    - name: Populate instance config
      set_fact:
        instance_conf: {}

    - name: Dump instance config
      copy:
        content: "{{ instance_conf | to_json | from_json | molecule_to_yaml | molecule_header }}"
        dest: "{{ molecule_instance_config }}"
      when: server.changed | bool
