I have a IAM role (with many policies and a trust relationship in it). I used this in building a AWS Cognito User Pool. However, this IAM role will be deleted soon.
Making a copy manually will be a chore and also not repeatable. I would like to make a copy either via CLI or script of some other repeatable way.
So far, I have searched through stackoverflow and google, but failed to find anything relevant.
Any help is appreciated.
It looks like you will need to use:
list_role_policies() to obtain the names of inline policies attached to the roleget_role_policy() to retrieve inline policieslist_attached_role_policies() to list managed policies that are attached to the roleThen create a new role and use:
put_role_policy() to attach an inline policyattach_role_policy() to attach a managed policyThanks to @JohnRotenstein for pointing in the right direction. I came up with a Node.js script to automate the IAM role copy procedure.
Steps it performs along with AWS SDK APIs used:
getRole()listRolePolicies(), getRolePolicy()listAttachedRolePolicies()createRole()putRolePolicy()attachRolePolicy()The process is quite straightforward... The only interesting detail is steps 2 and 3 require recursive fetch to accommodate the fact that policies response can be paginated.
If Python is an option, perhaps boto3 can be helpful (AWS's SDK for Python)
Creating a role: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/iam.html#IAM.Client.create_role
Creating a policy: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/iam.html#IAM.Client.create_policy
More: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/iam.html#client https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/iam.html