---
- hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - include_vars: "{{ item }}"
      with_first_found:
        - vars.yml
        - vars.yaml

    - name: Gather ec2 facts
      ec2_instance_facts:
        region: "{{ aws_region }}"
        filters:
          tag-key: "kubernetes.io/cluster/{{ aws_cluster_id }}"
      register: ec2

    - name: Terminate instances
      ec2:
        instance_ids: "{{ item.instance_id }}"
        region: "{{ aws_region }}"
        state: absent
        wait: yes
      with_items: "{{ ec2.instances }}"
      register: remove_instance
      until: remove_instance | success
      retries: 5
      delay: 10

    - name: Rename VMs
      ec2_tag:
        resource: "{{ item.instance_id }}"
        region: "{{ aws_region }}"
        tags:
          Name: "{{ item.tags.Name }}-terminate"
      with_items: "{{ ec2.instances }}"
      when:
        - aws_use_auto_terminator | default(true)
        - "'-terminate' not in item.tags.Name"
      register: rename_instance
      until: rename_instance | success
      retries: 5
      delay: 10

    - when: not aws_use_auto_terminator | default(true)
      block:
        - name: Find security groups
          ec2_group_facts:
            region: "{{ aws_region }}"
            filters:
              tag-key: "kubernetes.io/cluster/{{ aws_cluster_id }}"
          register: ec2_groups
        - name: Delete security groups
          ec2_group:
            name: "{{ item.group_id }}"
            state: absent
            region: "{{ aws_region }}"
          with_items: "{{ ec2_groups.security_groups }}"
          register: delete_sg
          until: delete_sg | success
          retries: 5
          delay: 10
