---
- name: 'Run integration tests for IAM (inline) Policy management'
  module_defaults:
    group/aws:
      aws_access_key: "{{ aws_access_key }}"
      aws_secret_key: "{{ aws_secret_key }}"
      security_token: "{{ security_token | default(omit) }}"
      region: "{{ aws_region }}"
  collections:
    - amazon.aws
  block:
    # ============================================================
    - name: Create a temporary folder for the policies
      tempfile:
        state: directory
      register: tmpdir
    - name: Copy over policy
      copy:
        src: no_access.json
        dest: "{{ tmpdir.path }}"
    - name: Copy over other policy
      copy:
        src: no_access_with_id.json
        dest: "{{ tmpdir.path }}"
    - name: Copy over other policy
      copy:
        src: no_access_with_second_id.json
        dest: "{{ tmpdir.path }}"

    # ============================================================
    - name: Create user for tests
      iam_user:
        state: present
        name: "{{ iam_name }}"
      register: result
    - name: Ensure user was created
      assert:
        that:
          - result is changed

    - name: Create role for tests
      iam_role:
        state: present
        name: "{{ iam_name }}"
        assume_role_policy_document: "{{ lookup('file','no_trust.json') }}"
      register: result
    - name: Ensure role was created
      assert:
        that:
          - result is changed

    - name: Create group for tests
      iam_group:
        state: present
        name: "{{ iam_name }}"
      register: result
    - name: Ensure group was created
      assert:
        that:
          - result is changed

    # ============================================================

    - name: Run tests for each type of object
      include_tasks: object.yml
      loop_control:
        loop_var: iam_type
      with_items:
        - user
        - group
        - role

    # ============================================================

  always:
    # ============================================================
    - name: Remove user
      iam_user:
        state: absent
        name: "{{ iam_name }}"
      ignore_errors: yes

    - name: Remove role
      iam_role:
        state: absent
        name: "{{ iam_name }}"
      ignore_errors: yes

    - name: Remove group
      iam_group:
        state: absent
        name: "{{ iam_name }}"
      ignore_errors: yes

    # ============================================================
    - name: Delete temporary folder containing the policies
      file:
        state: absent
        path: "{{ tmpdir.path }}/"
