---

- name: Query for {{ resource.apis | map(attribute='kind') | join(', ') }} resources with selector {{ label_selector }} to delete
  k8s_facts:
    api_version: "{{ to_delete_item.api_version | default(omit) }}"
    kind: "{{ to_delete_item.kind }}"
    namespace: "{{ namespace }}"
    label_selectors:
      - "{{ label_selector }}"
  loop: "{{ resource.apis }}"
  loop_control:
    loop_var: to_delete_item
  vars:
    label_selector: "{{ meteringconfig_prune_label_key }}={{ resource.prune_label_value }},{{ meteringconfig_prune_namespace_label_key }}={{ namespace }}"
  register: to_delete

- name: Delete {{ resource.apis | map(attribute='kind') | join(', ') }} resources with selector {{ label_selector}}
  k8s:
    state: absent
    definition: "{{ to_delete_results }}"
  vars:
    to_delete_results: "{{ to_delete.results | map(attribute='resources') | flatten }}"
    label_selector: "{{ meteringconfig_prune_label_key }}={{ resource.prune_label_value }},{{ meteringconfig_prune_namespace_label_key }}={{ namespace }}"
  when: to_delete_results | length > 0
