---
- name: Build Operator in Kubernetes docker container
  hosts: k8s
  collections:
    - community.kubernetes

  vars:
    image: test.example.com/ansible:testing

  tasks:
    # using command so we don't need to install any dependencies
    - name: Get existing image hash
      command: docker images -q {{ image }}
      register: prev_hash_raw
      changed_when: false

    - name: Build Operator Image
      command: docker build -f /build/build/Dockerfile -t {{ image }} /build
      register: build_cmd
      changed_when: not hash or (hash and hash not in cmd_out)
      vars:
        hash: '{{ prev_hash_raw.stdout }}'
        cmd_out: '{{ "".join(build_cmd.stdout_lines[-2:]) }}'

- name: Converge
  hosts: localhost
  connection: local
  collections:
    - community.kubernetes

  vars:
    image: test.example.com/ansible:testing
    operator_template: "{{ '/'.join([template_dir, 'operator.yaml.j2']) }}"

  tasks:
    - name: Create the Operator Deployment
      k8s:
        namespace: '{{ namespace }}'
        definition: "{{ lookup('template', operator_template) }}"
        wait: yes
      vars:
        pull_policy: Never
