---
# yamllint disable rule:line-length
- name: Update platforms
  hosts: localhost
  tasks:
    - name: Filtering platforms list using the group defined in the MOLECULE_GROUP environment variable
      set_fact:
        molecule_yml: "{{ molecule_yml | combine({'platforms': (molecule_yml.platforms | selectattr('groups', 'contains', lookup('env', 'MOLECULE_GROUP')))}) }}"
      when: ansible_env.MOLECULE_GROUP is defined

- name: Destroy
  hosts: localhost
  connection: local
  gather_facts: false
  no_log: '{{ molecule_no_log }}'
  tasks:
    - name: Destroy molecule instance(s)
      vagrant:
        instance_name: '{{ item.name }}'
        platform_box: '{{ item.box | default(omit) }}'
        provider_name: '{{ molecule_yml.driver.provider.name | default(omit, true) }}'
        provider_options: '{{ item.provider_options | default(omit) }}'
        provider_raw_config_args: '{{ item.provider_raw_config_args | default(omit) }}'
        force_stop: '{{ item.force_stop | default(true) }}'
        state: destroy
      register: server
      with_items: '{{ molecule_yml.platforms }}'
      loop_control:
        label: '{{ item.name }}'
      no_log: false

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

    - name: Dump instance config # noqa 503
      copy:
        content: |
          # Molecule managed
          {{ instance_conf | to_json | from_json | to_yaml }}
        dest: '{{ molecule_instance_config }}'
        mode: 0600
      when: server.changed | bool