---
- name: Check efs current replica count
  command: >
    {{ openshift.common.client_binary }} --config={{ mktemp.stdout }}/admin.kubeconfig get dc provisioners-efs
    -o jsonpath='{.spec.replicas}' -n {{openshift_provisioners_project}}
  register: efs_replica_count
  when: not ansible_check_mode
  ignore_errors: yes
  changed_when: no

- name: Generate efs PersistentVolumeClaim
  template: src=pvc.j2 dest={{mktemp.stdout}}/templates/{{obj_name}}-pvc.yaml
  vars:
    obj_name: "provisioners-efs"
    size: "1Mi"
    access_modes:
      - "ReadWriteMany"
    pv_selector:
      provisioners-efs: efs
  check_mode: no
  changed_when: no

- name: Generate efs PersistentVolume
  template: src=pv.j2 dest={{mktemp.stdout}}/templates/{{obj_name}}-pv.yaml
  vars:
    obj_name: "provisioners-efs"
    size: "1Mi"
    access_modes:
      - "ReadWriteMany"
    labels:
      provisioners-efs: efs
    volume_plugin: "nfs"
    volume_source:
      - {key: "server", value: "{{openshift_provisioners_efs_fsid}}.efs.{{openshift_provisioners_efs_region}}.amazonaws.com"}
      - {key: "path", value: "{{openshift_provisioners_efs_path}}"}
    claim_name: "provisioners-efs"
  check_mode: no
  changed_when: no

- name: Generate efs DeploymentConfig
  template:
    src: efs.j2
    dest: "{{ mktemp.stdout }}/templates/{{deploy_name}}-dc.yaml"
  vars:
    name: efs
    deploy_name: "provisioners-efs"
    deploy_serviceAccount: "provisioners-efs"
    replica_count: "{{efs_replica_count.stdout | default(0)}}"
    node_selector: "{{openshift_provisioners_efs_nodeselector | default('') }}"
    claim_name: "provisioners-efs"
  check_mode: no
  changed_when: false

# anyuid in order to run as root & chgrp shares with allocated gids
- name: "Check efs anyuid permissions"
  command: >
    {{ openshift.common.client_binary }} --config={{ mktemp.stdout }}/admin.kubeconfig
    get scc/anyuid -o jsonpath='{.users}'
  register: efs_anyuid
  check_mode: no
  changed_when: no

- name: "Set anyuid permissions for efs"
  command: >
    {{ openshift.common.admin_binary}} --config={{ mktemp.stdout }}/admin.kubeconfig policy
    add-scc-to-user anyuid system:serviceaccount:{{openshift_provisioners_project}}:provisioners-efs
  register: efs_output
  failed_when: efs_output.rc == 1 and 'exists' not in efs_output.stderr
  check_mode: no
  when: efs_anyuid.stdout.find("system:serviceaccount:" + openshift_provisioners_project + ":provisioners-efs") == -1
