---
- block:
    - name: ensure that k8s-log namespace exists
      k8s:
        kind: Namespace
        name: k8s-log

    - name: create hello-world deployment
      k8s:
        wait: yes
        definition:
          apiVersion: apps/v1
          kind: Deployment
          metadata:
            name: hello-world
            namespace: k8s-log
          spec:
            selector:
              matchLabels:
                app: hello-world
            template:
              metadata:
                labels:
                  app: hello-world
              spec:
                containers:
                  - image: busybox
                    name: hello-world
                    command: ['sh']
                    args: ['-c', 'while true ; do echo "hello world" && sleep 10 ; done']
                restartPolicy: Always

    - name: retrieve the log by providing the deployment
      k8s_log:
        api_version: apps/v1
        kind: Deployment
        namespace: k8s-log
        name: hello-world
      register: deployment_log

    - name: verify that the log can be retrieved via the deployment
      assert:
        that:
          - "'hello world' in deployment_log.log"
          - item == 'hello world' or item == ''
      with_items: '{{ deployment_log.log_lines }}'

    - name: retrieve the log with a label selector
      k8s_log:
        namespace: k8s-log
        label_selectors:
          - 'app=hello-world'
      register: label_selector_log

    - name: verify that the log can be retrieved via the label
      assert:
        that:
          - "'hello world' in label_selector_log.log"
          - item == 'hello world' or item == ''
      with_items: '{{ label_selector_log.log_lines }}'

    - name: get the hello-world pod
      k8s_info:
        kind: Pod
        namespace: k8s-log
        label_selectors:
          - 'app=hello-world'
      register: k8s_log_pods

    - name: retrieve the log directly with the pod name
      k8s_log:
        namespace: k8s-log
        name: '{{ k8s_log_pods.resources.0.metadata.name }}'
      register: pod_log

    - name: verify that the log can be retrieved via the pod name
      assert:
        that:
          - "'hello world' in pod_log.log"
          - item == 'hello world' or item == ''
      with_items: '{{ pod_log.log_lines }}'
  always:
    - name: ensure that namespace is removed
      k8s:
        kind: Namespace
        name: k8s-log
        state: absent
