---
- name: Fetch IAM idenity
  set_fact:
    iam_identity: "{{ lookup('iam_identity') | replace (',', '') }}"

- name: Create IAM user for cloudprovider_kind
  iam:
    iam_type: user
    name: "{{ clusterid }}.{{ dns_domain }}-admin"
    state: present
    access_key_state: create
  register: cpkuser

- name: "Pause for 15s to allow for IAM to refresh"
  pause:
    seconds: 15
  when: cpkuser.changed

- name: Land IAM cloudprovider_kind access key into file
  blockinfile:
    path: "~/.ssh/config-{{ clusterid }}.{{ dns_domain }}-cpkuser_access_key"
    create: yes
    marker: "<!-- {mark} OUTPUT -->"
    content: |
      openshift_cloudprovider_aws_access_key={{ cpkuser.user_meta.access_keys[0].access_key_id }}
      openshift_cloudprovider_aws_secret_key={{ cpkuser.user_meta.access_keys[0].secret_access_key }}
  when: cpkuser.changed

- name: Create IAM policy for cloudprovider_kind
  iam_policy:
    iam_type: user
    iam_name: "{{ clusterid }}.{{ dns_domain }}-admin"
    policy_name: "Admin"
    state: present
    policy_json: "{{ lookup('template', playbook_dir + '/roles/aws/templates/iam_policy_cpkuser.json.j2') }}"

- name: Create IAM user for Registry S3 storage
  iam:
    iam_type: user
    name: "{{ clusterid }}.{{ dns_domain }}-registry"
    state: present
    access_key_state: create
  register: s3user

- name: "Pause for 15s to allow for IAM to refresh"
  pause:
    seconds: 15
  when: s3user.changed

- name: Land IAM s3user access key into file
  blockinfile:
    path: "~/.ssh/config-{{ clusterid }}.{{ dns_domain }}-s3user_access_key"
    create: yes
    marker: "<!-- {mark} OUTPUT -->"
    content: |
      openshift_hosted_registry_storage_s3_accesskey={{ s3user.user_meta.access_keys[0].access_key_id }}
      openshift_hosted_registry_storage_s3_secretkey={{ s3user.user_meta.access_keys[0].secret_access_key }}
  when: s3user.changed

- name: Create IAM policy for S3 bucket user
  iam_policy:
    iam_type: user
    iam_name: "{{ clusterid }}.{{ dns_domain }}-registry"
    policy_name: "S3"
    state: present
    policy_json: "{{ lookup('template', playbook_dir + '/roles/aws/templates/iam_policy_s3user.json.j2') }}"
