How to import existing IAM Roles in AWS CDK


Borislav Hadzhiev

Mon Apr 26 20212 min read

Importing Existing IAM Roles in AWS CDK #

In order to import an existing IAM Role in CDK, we have to use the fromRoleArn static method on the Role construct.

import * as iam from '@aws-cdk/aws-iam'; import * as cdk from '@aws-cdk/core'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); // ๐Ÿ‘‡ import existing IAM Role const importedRole = iam.Role.fromRoleArn( this, 'imported-role', `arn:aws:iam::${cdk.Stack.of(this).account}:role/Existing-Role-Name`, {mutable: false}, ); console.log('importedRole ๐Ÿ‘‰', importedRole.roleName); } }

In the code snippet we've used the fromRoleArn method to import an external IAM Role in our CDK stack. The third parameter we've passed to the method is the ARN of the IAM role we want to import.

The mutable prop specifies whether the imported role can be modified by attaching policies to it. By default the mutable prop is set to true.

It doesn't make much sense to import a role and then modify its permissions, so most of the time it's best to avoid this behavior.

If I run the cdk synth command to run the code from the snippet with a role ARN that exists in my account, I can see that the role name is resolved at synthesis time:

role name resolved

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee