How to import existing IAM Roles in AWS CDK

avatar

Borislav Hadzhiev

Thu Apr 14 20222 min read

Updated - Thu Apr 14 2022

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-lib/aws-iam'; import * as cdk from 'aws-cdk-lib'; 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); } }

We used the fromRoleArn method to import an external IAM Role in our CDK stack. The third parameter we 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 #

Use the search field on my Home Page to filter through my more than 1,000 articles.