Clean Up AWS Resources Using Ansible - AWS IAM
Tags: aws, ansible, cloud, automation
Published: 2022-03-30 08:47:03

In case you have followed all the steps from Part 2 to Part 5 and you wanna remove them all. Here I'll show you how to do it. I'll add variables and tasks for deletion in one tag. If you just wanna delete a specific task, you can add and use more specific tags just like the creation tasks.

**The main points of this deletion process are:**

1. Use the same module, then change the state from present to absent.
    
2. We have to remove the policy first before we delete a user, group, or even role.
    
3. We have to remove the group's members first before we delete a group.
    
4. We have to remove the login profile and access key (if exist) before we delete a user.
    

Why do we have to do all of them? Because access through CLI is not as simple as Console we can do anything directly.

Alright, all we need is just 2 simple things before we are ready to run the playbook.

## 1\. Access Key of All Users

We have 6 users created in total and all of them have access keys. So we need to delete the access key first. To run the delete access key task, we need the access key value of each user. Remember that we have a file named `key_list.txt` that contains all users' access keys and secret access keys. So, we can copy directly from the file or we can simply run the following task to get more simple output from the file (optional).

```yaml
    - name: list user's key
      shell: 'cat key_list.txt | grep "UserName\|AccessKeyId" | awk "{ print $2 }" | sed "s/,$//"'
      register: output_key
      tags:
        - iam_user_key_list

    - debug:
        var: output_key.stdout_lines
      tags:
        - iam_user_key_list
```

```bash
$ ansible-playbook -i host.yml iam.yml -t iam_user_key_list

PLAY [iam] *********************************************************************

TASK [list user's key] *********************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "output_key.stdout_lines": [
        "        \"UserName\": \"name1\"",
        "        \"AccessKeyId\": \"AKIAZ44MXOFLL5MRZWON\"",
        "        \"UserName\": \"name2\"",
        "        \"AccessKeyId\": \"AKIAZ44MXOFLL36LYJKV\"",
        "        \"UserName\": \"name3\"",
        "        \"AccessKeyId\": \"AKIAZ44MXOFLCMV33DHV\"",
        "        \"UserName\": \"name4\"",
        "        \"AccessKeyId\": \"AKIAZ44MXOFLDJASSSVD\"",
        "        \"UserName\": \"name5\"",
        "        \"AccessKeyId\": \"AKIAZ44MXOFLNSZ6RO3F\"",
        "        \"UserName\": \"name6\"",
        "        \"AccessKeyId\": \"AKIAZ44MXOFLB6U2TTEU\""
    ]
}
```

## 2\. Create deletion tasks

**Note**\*: Please update the access key values of `delete user's key` task.

```yaml
    - name: remove all managed policies from role
      community.aws.iam_role:
        name: "{{ item.name }}"
        assume_role_policy_document: "{{ item.file }}"
        managed_policies: []
      loop: 
        - { name: IAM_Policy, file: "{{ lookup('file','role_policy.json') }}" }
      tags:
        - iam_deletion 

    - name: delete role
      community.aws.iam_role:
        name: "{{ item.name }}"
        assume_role_policy_document: "{{ item.file }}"
        state: absent
      loop: 
        - { name: IAM, file: "{{ lookup('file','role_policy.json') }}" }
        - { name: IAM_Policy, file: "{{ lookup('file','role_policy.json') }}" }
      tags:
        - iam_deletion

    - name: remove all group members from group with policy attached
      community.aws.iam_group:
        name: "{{ item.name }}"
        managed_policies: "{{ item.policy }}"
        purge_users: true
        state: present
      loop: 
        - { name: "{{ group3 }}", policy: arn:aws:iam::aws:policy/IAMReadOnlyAccess }
        - { name: "{{ group1 }}", policy: arn:aws:iam::01234567890:policy/IAMGetUser_Only }
      tags:
        - iam_deletion

    - name: remove all policies from group
      community.aws.iam_group:
        name: "{{ item.name }}"
        purge_policies: true
        state: present
      loop: 
        - { name: "{{ group1 }}" }
        - { name: "{{ group2 }}" }
        - { name: "{{ group3 }}" }
      tags:
        - iam_deletion

    - name: remove all policies from user
      community.aws.iam_user:
        name: "{{ item.name }}"
        purge_policies: true
        state: present
      loop: 
        - { name: "{{ user5 }}" }
        - { name: "{{ user3 }}" }
      tags:
        - iam_deletion

    - name: delete inline policy
      community.aws.iam_policy:
        iam_type: user
        iam_name: "{{ item.user }}"
        policy_name: "{{ item.name }}"
        state: absent
      loop: 
        - { name: IAMListUsers_Roles, user: "{{ user6 }}" }
      tags:
        - iam_deletion 

    - name: delete managed policy
      community.aws.iam_managed_policy:
        policy_name: "{{ item.name }}"
        state: absent
      loop: 
        - { name: IAMGetUser_Only }
      tags:
        - iam_deletion

    - name: delete user's login profile
      command: aws iam delete-login-profile --user-name "{{ item.name }}"
      loop: 
        - { name: "{{ user1 }}" }
        - { name: "{{ user2 }}" }
        - { name: "{{ user3 }}" }
        - { name: "{{ user4 }}" }
      tags:
        - iam_deletion

    - name: delete user's key
      command: aws iam delete-access-key --user-name "{{ item.name }}" --access-key-id "{{ item.key }}"
      loop: 
        - { name: "{{ user1 }}", key: AKIAZ44MXOFLL5MRZWON }
        - { name: "{{ user2 }}", key: AKIAZ44MXOFLL36LYJKV }
        - { name: "{{ user3 }}", key: AKIAZ44MXOFLCMV33DHV }
        - { name: "{{ user4 }}", key: AKIAZ44MXOFLDJASSSVD }
        - { name: "{{ user5 }}", key: AKIAZ44MXOFLNSZ6RO3F }
        - { name: "{{ user6 }}", key: AKIAZ44MXOFLB6U2TTEU }
      tags:
        - iam_deletion

    - name: delete all users
      community.aws.iam_user:
        name: "{{ item }}"
        state: absent
      loop: 
        - "{{ user1 }}"
        - "{{ user2 }}"
        - "{{ user3 }}"
        - "{{ user4 }}"
        - "{{ user5 }}"
        - "{{ user6 }}"
      tags:
        - iam_deletion

    - name: delete all groups
      community.aws.iam_group:
        name: "{{ item }}"
        state: absent
      loop: 
        - "{{ group1 }}"
        - "{{ group2 }}"
        - "{{ group3 }}"
      tags:
        - iam_deletion
```

## 3\. Run the Playbook

```bash
$ ansible-playbook -i host.yml iam.yml -t iam_deletion

PLAY [iam] *********************************************************************

TASK [remove all managed policies from role] ***********************************
changed: [localhost] => (item={'name': 'IAM_Policy', 'file': {'Version': '2012-10-17', 'Statement': [{'Effect': 'Allow', 'Action': 'sts:AssumeRole', 'Principal': {'AWS': 'arn:aws:iam::680510583126:user/name5'}}]}})

TASK [delete role] *************************************************************
changed: [localhost] => (item={'name': 'IAM', 'file': '{\n    "Version": "2012-10-17",\n    "Statement": [\n        {\n            "Effect": "Allow",\n            "Action": "sts:AssumeRole",\n            "Principal": { "AWS": "arn:aws:iam::"{{ role_account_id }}":user/"{{ role_user }}"" },\n        }\n    ]\n}'})
changed: [localhost] => (item={'name': 'IAM_Policy', 'file': '{\n    "Version": "2012-10-17",\n    "Statement": [\n        {\n            "Effect": "Allow",\n            "Action": "sts:AssumeRole",\n            "Principal": { "AWS": "arn:aws:iam::"{{ role_account_id }}":user/"{{ role_user }}"" },\n        }\n    ]\n}'})

TASK [remove all group members from group with policy attached] ****************
changed: [localhost] => (item={'name': 'engineer', 'policy': 'arn:aws:iam::aws:policy/IAMReadOnlyAccess'})
changed: [localhost] => (item={'name': 'developer', 'policy': 'arn:aws:iam::680510583126:policy/IAMGetUser_Only'})

TASK [remove all policies from group] ******************************************
changed: [localhost] => (item={'name': 'developer'})
changed: [localhost] => (item={'name': 'programmer'})
changed: [localhost] => (item={'name': 'engineer'})

TASK [remove all policies from user] *******************************************
changed: [localhost] => (item={'name': 'name5'})
changed: [localhost] => (item={'name': 'name3'})

TASK [delete inline policy] ****************************************************
changed: [localhost] => (item={'name': 'IAMListUsers_Roles', 'user': 'name6'})

TASK [delete managed policy] ***************************************************
changed: [localhost] => (item={'name': 'IAMGetUser_Only'})

TASK [delete user's login profile] *********************************************
changed: [localhost] => (item={'name': 'name1', 'pass': 'passwordup2U!'})
changed: [localhost] => (item={'name': 'name2', 'pass': 'passwordup2U!'})
changed: [localhost] => (item={'name': 'name3', 'pass': 'passwordup2U!'})
changed: [localhost] => (item={'name': 'name4', 'pass': 'passwordup2U!'})

TASK [delete user's key] *******************************************************
changed: [localhost] => (item={'name': 'name1', 'key': 'AKIAZ44MXOFLL5MRZWON'})
changed: [localhost] => (item={'name': 'name2', 'key': 'AKIAZ44MXOFLL36LYJKV'})
changed: [localhost] => (item={'name': 'name3', 'key': 'AKIAZ44MXOFLCMV33DHV'})
changed: [localhost] => (item={'name': 'name4', 'key': 'AKIAZ44MXOFLDJASSSVD'})
changed: [localhost] => (item={'name': 'name5', 'key': 'AKIAZ44MXOFLNSZ6RO3F'})
changed: [localhost] => (item={'name': 'name6', 'key': 'AKIAZ44MXOFLB6U2TTEU'})

TASK [delete all users] ********************************************************
changed: [localhost] => (item=name1)
changed: [localhost] => (item=name2)
changed: [localhost] => (item=name3)
changed: [localhost] => (item=name4)
changed: [localhost] => (item=name5)
changed: [localhost] => (item=name6)

TASK [delete all groups] *******************************************************
changed: [localhost] => (item=developer)
changed: [localhost] => (item=programmer)
changed: [localhost] => (item=engineer)
```

That's a wrap! Thanks for following all parts of this series. Follow me to get notified when a new post is published by me! Thank you!