- name: Checking plugin '{{ item.plugin }}'
  ansible.builtin.shell:
    cmd: 'set -o pipefail && microk8s.status --format short | grep {{ item.plugin }} | awk ''{split($0,a,": "); print(a[2]);}'''
    executable: /bin/bash
  register: plugin_status
  changed_when: false

- name: Enable plugin '{{ item.plugin }}'
  when: plugin_status.stdout == "disabled" and item.enabled
  block:
    - name: Compose microk8s command args
      ansible.builtin.set_fact:
        micro_k8s_args: "{{ (item.args | length > 0) | ternary(item.plugin + ':' + item.args, item.plugin) }}"

    - name: Enabling plugin '{{ item.plugin }}' # noqa no-changed-when
      ansible.builtin.command:
        cmd: "microk8s.enable {{ micro_k8s_args }}"

    - name: Waiting for plugin to apply '{{ item.wait }}'
      ansible.builtin.pause:
        seconds: "{{ item.wait }}"

- name: Disable plugin '{{ item.plugin }}'
  when: plugin_status.stdout == "enabled" and not item.enabled
  block:
    - name: Compose microk8s command args
      ansible.builtin.set_fact:
        micro_k8s_args: "{{ (item.args | length > 0) | ternary(item.plugin + ':' + item.args, item.plugin) }}"

    - name: Disable plugin '{{ item.plugin }}' # noqa no-changed-when
      ansible.builtin.command:
        cmd: "microk8s.disable {{ micro_k8s_args }}"

    - name: Waiting for plugin to apply '{{ item.wait }}'
      ansible.builtin.pause:
        seconds: "{{ item.wait }}"
