Borislav Hadzhiev
Last updated: Apr 14, 2022
Check out my new book
In order to import an existing IAM User in AWS CDK, we have to use the
fromUser*
static methods on the
User
class:
The most common method to import an existing IAM User in CDK is by the username.
To import a user by the username in CDK, we have to use the fromUserName
static method on the User
class.
import * as cdk from 'aws-cdk-lib'; import * as iam from 'aws-cdk-lib/aws-iam'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); // 👇 User imported by username const userByName = iam.User.fromUserName( this, 'user-by-name', 'YOUR_USER_NAME', ); console.log('user name 👉', userByName.userName); } }
We used the fromUserName
static method on the User
class to import an
existing IAM user into our CDK stack.
The fromUserName method takes the following parameters:
scope
- the scope the construct in instantiated inid
- the id of the construct (must be unique within the scope)userName
- the username of the existing IAM userIf I run the synth
command, having replaced the placeholder with an existing
IAM username, I can see that the user is successfully imported and the
userName
is resolved at synthesis time.
In order to import an existing IAM User by ARN in CDK, we have to use the
fromUserArn
static method on the User
class.
import * as cdk from 'aws-cdk-lib'; import * as iam from 'aws-cdk-lib/aws-iam'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); const userByArn = iam.User.fromUserArn( this, 'user-by-arn', `arn:aws:iam::${cdk.Stack.of(this).account}:user/YOUR_USER_NAME`, ); console.log('user name 👉', userByArn.userName); } }
The third parameter the fromUserArn
method takes is the ARN of the existing
IAM user.
In order to import an existing IAM User by user attributes in CDK, we have to
use the fromUserAttributes
method on the User
class.
At the time of writing the only supported user attribute is userArn
-
docs.
There is no good reason to use the fromUserAttributes
method over
fromUserArn
, but I'm including this snippet for completeness sake.
import * as cdk from 'aws-cdk-lib'; import * as iam from 'aws-cdk-lib/aws-iam'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); const userByAttributes = iam.User.fromUserAttributes( this, 'user-by-attributes', { userArn: `arn:aws:iam::${ cdk.Stack.of(this).account }:user/YOUR_USER_NAME`, }, ); console.log('user name 👉', userByAttributes.userName); } }
The third parameter the fromUserAttributes
takes is a map of user attributes
names and values. However, the only supported user attribute is the userArn
.
It's better to use the fromUserArn
method over fromUserAttributes
because
it more clearly conveys the intent of our code.