18

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.

Mamun
  • 2,322
  • 4
  • 27
  • 41

3 Answers3

6

It looks like you will need to use:

Then create a new role and use:

Trust Relationship also has to be copied.

Community
  • 1
  • 1
John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
6

Thanks 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:

  1. Fetch the source role along with its trust relationship policy: getRole()
  2. Fetch inline policies of the source role: listRolePolicies(), getRolePolicy()
  3. Fetch managed policies of the source role (both AWS- and customer-created): listAttachedRolePolicies()
  4. Create a new role copying over all relevant properties (including trust policy): createRole()
  5. Add all inline policies found in the source role to the new role: putRolePolicy()
  6. Attach all managed policies from the source role: 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.

How to make a copy of AWS IAM role.

Max Ivanov
  • 5,695
  • 38
  • 52
  • Hey Max, I just tried your script, and let me tell you it is pure love ❤️‍ Thanks for sharing it! – solr Aug 17 '21 at 16:08