---
- name: Converge
  hosts: localhost
  connection: local

  collections:
    - kubernetes.core

  vars_files:
    - vars/main.yml

  tasks:
    - name: Delete existing namespace
      k8s:
        api_version: v1
        kind: Namespace
        name: inventory
        wait: yes
        state: absent

    - name: Ensure namespace exists
      k8s:
        api_version: v1
        kind: Namespace
        name: inventory

    - name: Add a deployment
      k8s:
        definition:
          apiVersion: apps/v1
          kind: Deployment
          metadata:
            name: inventory
            namespace: inventory
          spec:
            replicas: 1
            selector:
              matchLabels:
                app: "{{ k8s_pod_name }}"
            template: "{{ k8s_pod_template }}"
        wait: yes
        wait_timeout: 400
      vars:
        k8s_pod_name: inventory
        k8s_pod_image: python
        k8s_pod_command:
          - python
          - '-m'
          - http.server
        k8s_pod_env:
          - name: TEST
            value: test

    - meta: refresh_inventory

- name: Verify inventory and connection plugins
  hosts: namespace_inventory_pods
  gather_facts: no

  vars:
    file_content: |
      Hello world

  tasks:
    - name: End play if host not running (TODO should we not add these to the inventory?)
      meta: end_host
      when: pod_phase != "Running"

    - debug: var=hostvars
    - setup:

    - debug: var=ansible_facts

    - name: Assert the TEST environment variable was retrieved
      assert:
        that: ansible_facts.env.TEST == 'test'

    - name: Copy a file into the host
      copy:
        content: '{{ file_content }}'
        dest: /tmp/test_file

    - name: Retrieve the file from the host
      slurp:
        src: /tmp/test_file
      register: slurped_file

    - name: Assert the file content matches expectations
      assert:
        that: (slurped_file.content|b64decode) == file_content
