---
- name: Terminate instance(s)
  hosts: localhost
  become: no
  connection: local
  gather_facts: no
  vars_files:
  - vars.yml
  tasks:
  - add_host:
      name: "{{ item }}"
      groups: oo_hosts_to_terminate
      ansible_ssh_user: "{{ deployment_vars[deployment_type].ssh_user }}"
      ansible_become: "{{ deployment_vars[deployment_type].become }}"
    with_items: "{{ (groups['meta-environment_' ~ cluster_env]|default([])) | intersect(groups['meta-clusterid_' ~ cluster_id ]|default([])) }}"

- name: Unsubscribe VMs
  hosts: oo_hosts_to_terminate
  vars_files:
  - vars.yml
  roles:
  - role: rhel_unsubscribe
    when: deployment_type in ['atomic-enterprise', 'enterprise', 'openshift-enterprise'] and
          ansible_distribution == "RedHat" and
          lookup('oo_option', 'rhel_skip_subscription') | default(rhsub_skip, True) |
            default('no', True) | lower in ['no', 'false']

- hosts: localhost
  become: no
  connection: local
  gather_facts: no
  vars_files:
  - vars.yml
  tasks:
  - name: Delete the OpenStack Stack
    command: 'heat stack-delete openshift-ansible-{{ cluster_id }}-stack'
    register: stack_delete_result
    changed_when: stack_delete_result.rc == 0
    failed_when: stack_delete_result.rc != 0 and 'could not be found' not in stack_delete_result.stdout

  - name: Wait for the completion of the OpenStack Stack deletion
    shell: 'heat stack-show openshift-ansible-{{ cluster_id }}-stack | awk ''$2 == "stack_status" {print $4}'''
    when: stack_delete_result.changed
    register: stack_show_result
    until: stack_show_result.stdout != 'DELETE_IN_PROGRESS'
    retries: 60
    delay: 5
    failed_when: '"Stack not found" not in stack_show_result.stderr and
                   stack_show_result.stdout != "DELETE_COMPLETE"'
