# Adds ServiceAccount to add-ons that need them and do not have them defined
# This is done in order to avoid giving scc anyuid to the default ServiceAccount

- set_fact:
    add_on_file_path: "{{ istio_dir }}/install/kubernetes/addons/{{ add_on_name }}.yaml"

- name: Determine whether a ServiceAccount is present in the {{ add_on_name }} file
  command: grep 'serviceAccountName' {{ add_on_file_path }}
  register: go
  ignore_errors: true

- name: Add ServiceAccount to {{ add_on_name }} add-on for istio prior to version 0.6
  replace:
    path: "{{ istio_dir }}/install/kubernetes/addons/{{ add_on_name }}.yaml"
    regexp: '^(\s*)containers:\s*$'
    replace: '\1serviceAccountName: istio-{{ add_on_name }}-service-account\n\1containers:'
    backup: yes
  when:
    - go.stdout_lines | length == 0
    - istio_version_to_use.split(".")[0] | int == 0
    - istio_version_to_use.split(".")[1] | int < 6

- name: Add ServiceAccount to {{ add_on_name }} add-on
  replace:
    path: "{{ istio_dir }}/install/kubernetes/addons/{{ add_on_name }}.yaml"
    regexp: '^(\s*)containers:\s*$'
    replace: '\1serviceAccountName: {{ add_on_name }}\n\1containers:'
    backup: yes
  when:
    - go.stdout_lines | length == 0
    - (istio_version_to_use.split(".")[0] | int > 0) or
      (istio_version_to_use.split(".")[1] | int >= 6)

- set_fact:
    add_on_definition_path: /tmp/{{ add_on_name }}-service-account

- name: Apply ServiceAccount from template for {{ add_on_name }} for istio prior to version 0.6
  command: "{{ cmd_path }} create serviceaccount istio-{{ add_on_name }}-service-account -n istio-system"
  ignore_errors: true
  when:
    - istio_version_to_use.split(".")[0] | int == 0
    - istio_version_to_use.split(".")[1] | int < 6

- name: Apply ServiceAccount from template for {{ add_on_name }}
  command: "{{ cmd_path }} create serviceaccount {{ add_on_name }} -n istio-system"
  ignore_errors: true
  when:
    - (istio_version_to_use.split(".")[0] | int > 0) or
      (istio_version_to_use.split(".")[1] | int >= 6)

- name: Define SCC rules to enable containers running with UID zero for Addon service accounts for {{ add_on_name }} for istio prior to version 0.6
  command: "{{ cmd_path }} adm policy add-scc-to-user anyuid -z istio-{{ add_on_name }}-service-account -n istio-system"
  when:
    - cluster_flavour == 'ocp'
    - istio_version_to_use.split(".")[0] | int == 0
    - istio_version_to_use.split(".")[1] | int < 6

- name: Define SCC rules to enable containers running with UID zero for Addon service accounts for {{ add_on_name }}
  command: "{{ cmd_path }} adm policy add-scc-to-user anyuid -z {{ add_on_name }} -n istio-system"
  when:
    - cluster_flavour == 'ocp'
    - (istio_version_to_use.split(".")[0] | int > 0) or
      (istio_version_to_use.split(".")[1] | int >= 6)

