Skip to content
v2.273.0

AWS Identity and Access Management Construct Library ​

Security and Safety Dev Guide ​

For a detailed guide on CDK security and safety please see the CDK Security And Safety Dev Guide

The guide will cover topics like:

  • What permissions to extend to CDK deployments
  • How to control the permissions of CDK deployments via IAM identities and policies
  • How to use CDK to configure the IAM identities and policies of deployed applications
  • Using Permissions Boundaries with CDK

Overview ​

Define a role and add permissions to it. This will automatically create and attach an IAM policy to the role:

ts
    const role = new Role(this, 'MyRole', {
      assumedBy: new ServicePrincipal('sns.amazonaws.com'),
    });

    role.addToPolicy(new PolicyStatement({
      resources: ['*'],
      actions: ['lambda:InvokeFunction'],
    }));
python
role = Role(self, "MyRole",
    assumed_by=ServicePrincipal("sns.amazonaws.com")
)

role.add_to_policy(PolicyStatement(
    resources=["*"],
    actions=["lambda:InvokeFunction"]
))
java
Role role = Role.Builder.create(this, "MyRole")
        .assumedBy(new ServicePrincipal("sns.amazonaws.com"))
        .build();

role.addToPolicy(PolicyStatement.Builder.create()
        .resources(List.of("*"))
        .actions(List.of("lambda:InvokeFunction"))
        .build());
csharp
var role = new Role(this, "MyRole", new RoleProps {
    AssumedBy = new ServicePrincipal("sns.amazonaws.com")
});

role.AddToPolicy(new PolicyStatement(new PolicyStatementProps {
    Resources = new [] { "*" },
    Actions = new [] { "lambda:InvokeFunction" }
}));
go
role := awscdk.NewRole(this, jsii.String("MyRole"), &RoleProps{
	AssumedBy: awscdk.NewServicePrincipal(jsii.String("sns.amazonaws.com")),
})

role.AddToPolicy(awscdk.NewPolicyStatement(&PolicyStatementProps{
	Resources: []*string{
		jsii.String("*"),
	},
	Actions: []*string{
		jsii.String("lambda:InvokeFunction"),
	},
}))

Define a policy and attach it to groups, users and roles. Note that it is possible to attach the policy either by calling xxx.attachInlinePolicy(policy) or policy.attachToXxx(xxx).

ts
    const user = new User(this, 'MyUser', { password: SecretValue.plainText('1234') });
    const group = new Group(this, 'MyGroup');

    const policy = new Policy(this, 'MyPolicy');
    policy.attachToUser(user);
    group.attachInlinePolicy(policy);
python
user = User(self, "MyUser", password=SecretValue.plain_text("1234"))
group = Group(self, "MyGroup")

policy = Policy(self, "MyPolicy")
policy.attach_to_user(user)
group.attach_inline_policy(policy)
java
User user = User.Builder.create(this, "MyUser").password(SecretValue.plainText("1234")).build();
Group group = new Group(this, "MyGroup");

Policy policy = new Policy(this, "MyPolicy");
policy.attachToUser(user);
group.attachInlinePolicy(policy);
csharp
var user = new User(this, "MyUser", new UserProps { Password = SecretValue.PlainText("1234") });
var group = new Group(this, "MyGroup");

var policy = new Policy(this, "MyPolicy");
policy.AttachToUser(user);
group.AttachInlinePolicy(policy);
go
user := awscdk.NewUser(this, jsii.String("MyUser"), &UserProps{
	Password: awscdk.SecretValue_PlainText(jsii.String("1234")),
})
group := awscdk.NewGroup(this, jsii.String("MyGroup"))

policy := awscdk.NewPolicy(this, jsii.String("MyPolicy"))
policy.AttachToUser(user)
group.attachInlinePolicy(policy)

Managed policies can be attached using xxx.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName)):

ts
const group = new Group(this, 'MyGroup');
group.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName('AdministratorAccess'));
python
group = Group(self, "MyGroup")
group.add_managed_policy(ManagedPolicy.from_aws_managed_policy_name("AdministratorAccess"))
java
Group group = new Group(this, "MyGroup");
group.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName("AdministratorAccess"));
csharp
var group = new Group(this, "MyGroup");
group.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("AdministratorAccess"));
go
group := awscdk.NewGroup(this, jsii.String("MyGroup"))
group.AddManagedPolicy(awscdk.ManagedPolicy_FromAwsManagedPolicyName(jsii.String("AdministratorAccess")))

Granting permissions to resources ​

Many of the AWS CDK resources have grant methods (accessible via the grants attribute) that allow you to grant other resources access to that resource. As an example, the following code gives a Lambda function write permissions (Put, Update, Delete) to a DynamoDB table.

ts
declare const fn: lambda.Function;
declare const table: dynamodb.Table;

table.grants.writeData(fn);
python
# fn: lambda.Function
# table: dynamodb.Table


table.grants.write_data(fn)
java
Function fn;
Table table;


table.grants.writeData(fn);
csharp
Function fn;
Table table;


table.Grants.WriteData(fn);
go
var fn Function
var table Table


table.grants.WriteData(fn)

The more generic actions method allows you to give specific permissions to a resource:

ts
declare const fn: lambda.Function;
declare const table: dynamodb.Table;

table.grants.actions(fn, 'dynamodb:PutItem');
python
# fn: lambda.Function
# table: dynamodb.Table


table.grants.actions(fn, "dynamodb:PutItem")
java
Function fn;
Table table;


table.grants.actions(fn, "dynamodb:PutItem");
csharp
Function fn;
Table table;


table.Grants.Actions(fn, "dynamodb:PutItem");
go
var fn Function
var table Table


table.grants.Actions(fn, jsii.String("dynamodb:PutItem"))

The grant methods accept an IGrantable object. This interface is implemented by IAM principal resources (groups, users and roles), policies, managed policies and resources that assume a role such as a Lambda function, EC2 instance or a Codebuild project.

You can find which grant methods exist for a resource in the AWS CDK API Reference.

Roles ​

Many AWS resources require Roles to operate. These Roles define the AWS API calls an instance or other AWS service is allowed to make.

Creating Roles and populating them with the right permissions Statements is a necessary but tedious part of setting up AWS infrastructure. In order to help you focus on your business logic, CDK will take care of creating roles and populating them with least-privilege permissions automatically.

All constructs that require Roles will create one for you if don't specify one at construction time. Permissions will be added to that role automatically if you associate the construct with other constructs from the AWS Construct Library (for example, if you tell an AWS CodePipeline to trigger an AWS Lambda Function, the Pipeline's Role will automatically get lambda:InvokeFunction permissions on that particular Lambda Function), or if you explicitly grant permissions using the public methods in the RoleGrants class (see the previous section).

Opting out of automatic permissions management ​

You may prefer to manage a Role's permissions yourself instead of having the CDK automatically manage them for you. This may happen in one of the following cases:

  • You don't like the permissions that CDK automatically generates and want to substitute your own set.
  • The least-permissions policy that the CDK generates is becoming too big for IAM to store, and you need to add some wildcards to keep the policy size down.

To prevent constructs from updating your Role's policy, pass the object returned by myRole.withoutPolicyUpdates() instead of myRole itself.

For example, to have an AWS CodePipeline not automatically add the required permissions to trigger the expected targets, do the following:

ts
const role = new iam.Role(this, 'Role', {
  assumedBy: new iam.ServicePrincipal('codepipeline.amazonaws.com'),
  // custom description if desired
  description: 'This is a custom role...',
});

new codepipeline.Pipeline(this, 'Pipeline', {
  // Give the Pipeline an immutable view of the Role
  role: role.withoutPolicyUpdates(),
});

// You now have to manage the Role policies yourself
role.addToPolicy(new iam.PolicyStatement({
  actions: [/* whatever actions you want */],
  resources: [/* whatever resources you intend to touch */],
}));
python
role = iam.Role(self, "Role",
    assumed_by=iam.ServicePrincipal("codepipeline.amazonaws.com"),
    # custom description if desired
    description="This is a custom role..."
)

codepipeline.Pipeline(self, "Pipeline",
    # Give the Pipeline an immutable view of the Role
    role=role.without_policy_updates()
)

# You now have to manage the Role policies yourself
role.add_to_policy(iam.PolicyStatement(
    actions=[],
    resources=[]
))
java
Role role = Role.Builder.create(this, "Role")
        .assumedBy(new ServicePrincipal("codepipeline.amazonaws.com"))
        // custom description if desired
        .description("This is a custom role...")
        .build();

Pipeline.Builder.create(this, "Pipeline")
        // Give the Pipeline an immutable view of the Role
        .role(role.withoutPolicyUpdates())
        .build();

// You now have to manage the Role policies yourself
role.addToPolicy(PolicyStatement.Builder.create()
        .actions(List.of())
        .resources(List.of())
        .build());
csharp
var role = new Role(this, "Role", new RoleProps {
    AssumedBy = new ServicePrincipal("codepipeline.amazonaws.com"),
    // custom description if desired
    Description = "This is a custom role..."
});

new Pipeline(this, "Pipeline", new PipelineProps {
    // Give the Pipeline an immutable view of the Role
    Role = role.WithoutPolicyUpdates()
});

// You now have to manage the Role policies yourself
role.AddToPolicy(new PolicyStatement(new PolicyStatementProps {
    Actions = new [] {  },
    Resources = new [] {  }
}));
go
role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("codepipeline.amazonaws.com")),
	// custom description if desired
	Description: jsii.String("This is a custom role..."),
})

codepipeline.NewPipeline(this, jsii.String("Pipeline"), &PipelineProps{
	// Give the Pipeline an immutable view of the Role
	Role: role.WithoutPolicyUpdates(),
})

// You now have to manage the Role policies yourself
role.AddToPolicy(iam.NewPolicyStatement(&PolicyStatementProps{
	Actions: []*string{
	},
	Resources: []*string{
	},
}))

Using existing roles ​

If there are Roles in your account that have already been created which you would like to use in your CDK application, you can use Role.fromRoleArn to import them, as follows:

ts
const role = iam.Role.fromRoleArn(this, 'Role', 'arn:aws:iam::123456789012:role/MyExistingRole', {
  // Set 'mutable' to 'false' to use the role as-is and prevent adding new
  // policies to it. The default is 'true', which means the role may be
  // modified as part of the deployment.
  mutable: false,
});
python
role = iam.Role.from_role_arn(self, "Role", "arn:aws:iam::123456789012:role/MyExistingRole",
    # Set 'mutable' to 'false' to use the role as-is and prevent adding new
    # policies to it. The default is 'true', which means the role may be
    # modified as part of the deployment.
    mutable=False
)
java
IRole role = Role.fromRoleArn(this, "Role", "arn:aws:iam::123456789012:role/MyExistingRole", FromRoleArnOptions.builder()
        // Set 'mutable' to 'false' to use the role as-is and prevent adding new
        // policies to it. The default is 'true', which means the role may be
        // modified as part of the deployment.
        .mutable(false)
        .build());
csharp
var role = Role.FromRoleArn(this, "Role", "arn:aws:iam::123456789012:role/MyExistingRole", new FromRoleArnOptions {
    // Set 'mutable' to 'false' to use the role as-is and prevent adding new
    // policies to it. The default is 'true', which means the role may be
    // modified as part of the deployment.
    Mutable = false
});
go
role := iam.Role_FromRoleArn(this, jsii.String("Role"), jsii.String("arn:aws:iam::123456789012:role/MyExistingRole"), &FromRoleArnOptions{
	// Set 'mutable' to 'false' to use the role as-is and prevent adding new
	// policies to it. The default is 'true', which means the role may be
	// modified as part of the deployment.
	Mutable: jsii.Boolean(false),
})

If you want to lookup roles that actually exist in your account, you can use Role.fromLookup().

ts
const role = iam.Role.fromLookup(this, 'Role', {
  roleName: 'MyExistingRole',
});
python
role = iam.Role.from_lookup(self, "Role",
    role_name="MyExistingRole"
)
java
IRole role = Role.fromLookup(this, "Role", RoleLookupOptions.builder()
        .roleName("MyExistingRole")
        .build());
csharp
var role = Role.FromLookup(this, "Role", new RoleLookupOptions {
    RoleName = "MyExistingRole"
});
go
role := iam.Role_FromLookup(this, jsii.String("Role"), &RoleLookupOptions{
	RoleName: jsii.String("MyExistingRole"),
})

Customizing role creation ​

It is best practice to allow CDK to manage IAM roles and permissions. You can prevent CDK from creating roles by using the customizeRoles method for special cases. One such case is using CDK in an environment where role creation is not allowed or needs to be managed through a process outside of the CDK application.

An example of how to opt in to this behavior is below:

ts
declare const stack: Stack;
iam.Role.customizeRoles(stack);
python
# stack: Stack

iam.Role.customize_roles(stack)
java
Stack stack;

Role.customizeRoles(stack);
csharp
Stack stack;

Role.CustomizeRoles(stack);
go
var stack Stack

iam.Role_CustomizeRoles(stack)

CDK will not create any IAM roles or policies with the stack scope. cdk synth will fail and it will generate a policy report to the cloud assembly (i.e. cdk.out). The iam-policy-report.txt report will contain a list of IAM roles and associated permissions that would have been created. This report can be used to create the roles with the appropriate permissions outside of the CDK application.

Once the missing roles have been created, their names can be added to the usePrecreatedRoles property, like shown below:

ts
declare const app: App;
const stack = new Stack(app, 'MyStack');
iam.Role.customizeRoles(this, {
  usePrecreatedRoles: {
    'MyStack/MyRole': 'my-precreated-role-name',
  },
});

new iam.Role(this, 'MyRole', {
  assumedBy: new iam.ServicePrincipal('sns.amazonaws.com'),
});
python
# app: App

stack = Stack(app, "MyStack")
iam.Role.customize_roles(self,
    use_precreated_roles={
        "MyStack/MyRole": "my-precreated-role-name"
    }
)

iam.Role(self, "MyRole",
    assumed_by=iam.ServicePrincipal("sns.amazonaws.com")
)
java
App app;

Stack stack = new Stack(app, "MyStack");
Role.customizeRoles(this, CustomizeRolesOptions.builder()
        .usePrecreatedRoles(Map.of(
                "MyStack/MyRole", "my-precreated-role-name"))
        .build());

Role.Builder.create(this, "MyRole")
        .assumedBy(new ServicePrincipal("sns.amazonaws.com"))
        .build();
csharp
App app;

var stack = new Stack(app, "MyStack");
Role.CustomizeRoles(this, new CustomizeRolesOptions {
    UsePrecreatedRoles = new Dictionary<string, string> {
        { "MyStack/MyRole", "my-precreated-role-name" }
    }
});

new Role(this, "MyRole", new RoleProps {
    AssumedBy = new ServicePrincipal("sns.amazonaws.com")
});
go
var app App

stack := awscdk.Newstack(app, jsii.String("MyStack"))
iam.Role_CustomizeRoles(this, &CustomizeRolesOptions{
	UsePrecreatedRoles: map[string]*string{
		"MyStack/MyRole": jsii.String("my-precreated-role-name"),
	},
})

iam.NewRole(this, jsii.String("MyRole"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("sns.amazonaws.com")),
})

If any IAM policies reference deploy time values (i.e. ARN of a resource that hasn't been created yet) you will have to modify the generated report to be more generic. For example, given the following CDK code:

ts
declare const app: App;
const stack = new Stack(app, 'MyStack');
iam.Role.customizeRoles(stack);

const fn = new lambda.Function(this, 'MyLambda', {
  code: new lambda.InlineCode('foo'),
  handler: 'index.handler',
  runtime: lambda.Runtime.NODEJS_LATEST,
});

const bucket = new s3.Bucket(this, 'Bucket');
bucket.grants.read(fn);
python
# app: App

stack = Stack(app, "MyStack")
iam.Role.customize_roles(stack)

fn = lambda_.Function(self, "MyLambda",
    code=lambda_.InlineCode("foo"),
    handler="index.handler",
    runtime=lambda_.Runtime.NODEJS_LATEST
)

bucket = s3.Bucket(self, "Bucket")
bucket.grants.read(fn)
java
App app;

Stack stack = new Stack(app, "MyStack");
Role.customizeRoles(stack);

Function fn = Function.Builder.create(this, "MyLambda")
        .code(new InlineCode("foo"))
        .handler("index.handler")
        .runtime(Runtime.NODEJS_LATEST)
        .build();

Bucket bucket = new Bucket(this, "Bucket");
bucket.grants.read(fn);
csharp
App app;

var stack = new Stack(app, "MyStack");
Role.CustomizeRoles(stack);

var fn = new Function(this, "MyLambda", new FunctionProps {
    Code = new InlineCode("foo"),
    Handler = "index.handler",
    Runtime = Runtime.NODEJS_LATEST
});

var bucket = new Bucket(this, "Bucket");
bucket.Grants.Read(fn);
go
var app App

stack := awscdk.Newstack(app, jsii.String("MyStack"))
iam.Role_CustomizeRoles(stack)

fn := lambda.NewFunction(this, jsii.String("MyLambda"), &FunctionProps{
	Code: lambda.NewInlineCode(jsii.String("foo")),
	Handler: jsii.String("index.handler"),
	Runtime: lambda.Runtime_NODEJS_LATEST(),
})

bucket := s3.NewBucket(this, jsii.String("Bucket"))
bucket.grants.Read(fn)

The following report will be generated.

txt
<missing role> (MyStack/MyLambda/ServiceRole)

AssumeRole Policy:
[
  {
    "Action": "sts:AssumeRole",
    "Effect": "Allow",
    "Principal": {
      "Service": "lambda.amazonaws.com"
    }
  }
]

Managed Policy ARNs:
[
  "arn:(PARTITION):iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
]

Managed Policies Statements:
NONE

Identity Policy Statements:
[
  {
    "Action": [
      "s3:GetObject*",
      "s3:GetBucket*",
      "s3:List*"
    ],
    "Effect": "Allow",
    "Resource": [
      "(MyStack/Bucket/Resource.Arn)",
      "(MyStack/Bucket/Resource.Arn)/*"
    ]
  }
]

You would then need to create the role with the inline & managed policies in the report and then come back and update the customizeRoles with the role name.

ts
declare const app: App;
const stack = new Stack(app, 'MyStack');
iam.Role.customizeRoles(this, {
  usePrecreatedRoles: {
    'MyStack/MyLambda/ServiceRole': 'my-role-name',
  }
});
python
# app: App

stack = Stack(app, "MyStack")
iam.Role.customize_roles(self,
    use_precreated_roles={
        "MyStack/MyLambda/ServiceRole": "my-role-name"
    }
)
java
App app;

Stack stack = new Stack(app, "MyStack");
Role.customizeRoles(this, CustomizeRolesOptions.builder()
        .usePrecreatedRoles(Map.of(
                "MyStack/MyLambda/ServiceRole", "my-role-name"))
        .build());
csharp
App app;

var stack = new Stack(app, "MyStack");
Role.CustomizeRoles(this, new CustomizeRolesOptions {
    UsePrecreatedRoles = new Dictionary<string, string> {
        { "MyStack/MyLambda/ServiceRole", "my-role-name" }
    }
});
go
var app App

stack := awscdk.Newstack(app, jsii.String("MyStack"))
iam.Role_CustomizeRoles(this, &CustomizeRolesOptions{
	UsePrecreatedRoles: map[string]*string{
		"MyStack/MyLambda/ServiceRole": jsii.String("my-role-name"),
	},
})

For more information on configuring permissions see the Security And Safety Dev Guide

Policy report generation ​

When customizeRoles is used, the iam-policy-report.txt report will contain a list of IAM roles and associated permissions that would have been created. This report is generated in an attempt to resolve and replace any references with a more user-friendly value.

The following are some examples of the value that will appear in the report:

json
"Resource": {
  "Fn::Join": [
    "",
    [
      "arn:",
      {
        "Ref": "AWS::Partition"
      },
      ":iam::",
      {
        "Ref": "AWS::AccountId"
      },
      ":role/Role"
    ]
  ]
}

The policy report will instead get:

json
"Resource": "arn:(PARTITION):iam::(ACCOUNT):role/Role"

If IAM policy is referencing a resource attribute:

json
"Resource": [
  {
    "Fn::GetAtt": [
      "SomeResource",
      "Arn"
    ]
  },
  {
    "Ref": "AWS::NoValue",
  }
]

The policy report will instead get:

json
"Resource": [
  "(Path/To/SomeResource.Arn)"
  "(NOVALUE)"
]

The following pseudo parameters will be converted:

  1. { 'Ref': 'AWS::AccountId' } -> `(ACCOUNT)
  2. { 'Ref': 'AWS::Partition' } -> `(PARTITION)
  3. { 'Ref': 'AWS::Region' } -> `(REGION)
  4. { 'Ref': 'AWS::NoValue' } -> `(NOVALUE)

Generating a permissions report ​

It is also possible to generate the report without preventing the role/policy creation.

ts
declare const stack: Stack;
iam.Role.customizeRoles(this, {
  preventSynthesis: false,
});
python
# stack: Stack

iam.Role.customize_roles(self,
    prevent_synthesis=False
)
java
Stack stack;

Role.customizeRoles(this, CustomizeRolesOptions.builder()
        .preventSynthesis(false)
        .build());
csharp
Stack stack;

Role.CustomizeRoles(this, new CustomizeRolesOptions {
    PreventSynthesis = false
});
go
var stack Stack

iam.Role_CustomizeRoles(this, &CustomizeRolesOptions{
	PreventSynthesis: jsii.Boolean(false),
})

Configuring an ExternalId ​

If you need to create Roles that will be assumed by third parties, it is generally a good idea to require an ExternalId to assume them. Configuring an ExternalId works like this:

ts
const role = new iam.Role(this, 'MyRole', {
  assumedBy: new iam.AccountPrincipal('123456789012'),
  externalIds: ['SUPPLY-ME'],
});
python
role = iam.Role(self, "MyRole",
    assumed_by=iam.AccountPrincipal("123456789012"),
    external_ids=["SUPPLY-ME"]
)
java
Role role = Role.Builder.create(this, "MyRole")
        .assumedBy(new AccountPrincipal("123456789012"))
        .externalIds(List.of("SUPPLY-ME"))
        .build();
csharp
var role = new Role(this, "MyRole", new RoleProps {
    AssumedBy = new AccountPrincipal("123456789012"),
    ExternalIds = new [] { "SUPPLY-ME" }
});
go
role := iam.NewRole(this, jsii.String("MyRole"), &RoleProps{
	AssumedBy: iam.NewAccountPrincipal(jsii.String("123456789012")),
	ExternalIds: []*string{
		jsii.String("SUPPLY-ME"),
	},
})

SourceArn and SourceAccount ​

If you need to create resource policies using aws:SourceArn and aws:SourceAccount for cross-service resource access, use addSourceArnCondition and addSourceAccountCondition to create the conditions.

See Cross-service confused deputy prevention for more details.

Principals vs Identities ​

When we say Principal, we mean an entity you grant permissions to. This entity can be an AWS Service, a Role, or something more abstract such as "all users in this account" or even "all users in this organization". An Identity is an IAM representing a single IAM entity that can have a policy attached, one of Role, User, or Group.

IAM Principals ​

When defining policy statements as part of an AssumeRole policy or as part of a resource policy, statements would usually refer to a specific IAM principal under Principal.

IAM principals are modeled as classes that derive from the iam.PolicyPrincipal abstract class. Principal objects include principal type (string) and value (array of string), optional set of conditions and the action that this principal requires when it is used in an assume role policy document.

To add a principal to a policy statement you can either use the abstract statement.addPrincipal, one of the concrete addXxxPrincipal methods:

  • addAwsPrincipal, addArnPrincipal or new ArnPrincipal(arn) for { "AWS": arn }
  • addAwsAccountPrincipal or new AccountPrincipal(accountId) for { "AWS": account-arn }
  • addServicePrincipal or new ServicePrincipal(service) for { "Service": service }
  • addAccountRootPrincipal or new AccountRootPrincipal() for { "AWS": { "Ref: "AWS::AccountId" } }
  • addCanonicalUserPrincipal or new CanonicalUserPrincipal(id) for { "CanonicalUser": id }
  • addFederatedPrincipal or new FederatedPrincipal(federated, conditions, assumeAction) for { "Federated": arn } and a set of optional conditions and the assume role action to use.
  • addAnyPrincipal or new AnyPrincipal for { "AWS": "*" }

If multiple principals are added to the policy statement, they will be merged together:

ts
const statement = new iam.PolicyStatement();
statement.addServicePrincipal('cloudwatch.amazonaws.com');
statement.addServicePrincipal('ec2.amazonaws.com');
statement.addArnPrincipal('arn:aws:boom:boom');
python
statement = iam.PolicyStatement()
statement.add_service_principal("cloudwatch.amazonaws.com")
statement.add_service_principal("ec2.amazonaws.com")
statement.add_arn_principal("arn:aws:boom:boom")
java
PolicyStatement statement = new PolicyStatement();
statement.addServicePrincipal("cloudwatch.amazonaws.com");
statement.addServicePrincipal("ec2.amazonaws.com");
statement.addArnPrincipal("arn:aws:boom:boom");
csharp
var statement = new PolicyStatement();
statement.AddServicePrincipal("cloudwatch.amazonaws.com");
statement.AddServicePrincipal("ec2.amazonaws.com");
statement.AddArnPrincipal("arn:aws:boom:boom");
go
statement := iam.NewPolicyStatement()
statement.AddServicePrincipal(jsii.String("cloudwatch.amazonaws.com"))
statement.AddServicePrincipal(jsii.String("ec2.amazonaws.com"))
statement.AddArnPrincipal(jsii.String("arn:aws:boom:boom"))

Will result in:

json
{
  "Principal": {
    "Service": [ "cloudwatch.amazonaws.com", "ec2.amazonaws.com" ],
    "AWS": "arn:aws:boom:boom"
  }
}

The CompositePrincipal class can also be used to define complex principals, for example:

ts
const role = new iam.Role(this, 'MyRole', {
  assumedBy: new iam.CompositePrincipal(
    new iam.ServicePrincipal('ec2.amazonaws.com'),
    new iam.AccountPrincipal('1818188181818187272')
  ),
});
python
role = iam.Role(self, "MyRole",
    assumed_by=iam.CompositePrincipal(
        iam.ServicePrincipal("ec2.amazonaws.com"),
        iam.AccountPrincipal("1818188181818187272"))
)
java
Role role = Role.Builder.create(this, "MyRole")
        .assumedBy(new CompositePrincipal(
        new ServicePrincipal("ec2.amazonaws.com"),
        new AccountPrincipal("1818188181818187272")))
        .build();
csharp
var role = new Role(this, "MyRole", new RoleProps {
    AssumedBy = new CompositePrincipal(
    new ServicePrincipal("ec2.amazonaws.com"),
    new AccountPrincipal("1818188181818187272"))
});
go
role := iam.NewRole(this, jsii.String("MyRole"), &RoleProps{
	AssumedBy: iam.NewCompositePrincipal(
	iam.NewServicePrincipal(jsii.String("ec2.amazonaws.com")),
	iam.NewAccountPrincipal(jsii.String("1818188181818187272"))),
})

The PrincipalWithConditions class can be used to add conditions to a principal, especially those that don't take a conditions parameter in their constructor. The principal.withConditions() method can be used to create a PrincipalWithConditions from an existing principal, for example:

ts
const principal = new iam.AccountPrincipal('123456789000')
  .withConditions({ StringEquals: { foo: "baz" } });
python
principal = iam.AccountPrincipal("123456789000").with_conditions({"StringEquals": {"foo": "baz"}})
java
PrincipalBase principal = new AccountPrincipal("123456789000").withConditions(Map.of("StringEquals", Map.of("foo", "baz")));
csharp
var principal = new AccountPrincipal("123456789000").WithConditions(new Dictionary<string, object> { { "StringEquals", new Dictionary<string, string> { { "foo", "baz" } } } });
go
principal := iam.NewAccountPrincipal(jsii.String("123456789000")).WithConditions(map[string]interface{}{
	"StringEquals": map[string]*string{
		"foo": jsii.String("baz"),
	},
})

NOTE: If you need to define an IAM condition that uses a token (such as a deploy-time attribute of another resource) in a JSON map key, use CfnJson to render this condition. See this test for an example.

The WebIdentityPrincipal class can be used as a principal for web identities like Cognito, Amazon, Google or Facebook, for example:

ts
const principal = new iam.WebIdentityPrincipal('cognito-identity.amazonaws.com', {
  'StringEquals': { 'cognito-identity.amazonaws.com:aud': 'us-east-2:12345678-abcd-abcd-abcd-123456' },
  'ForAnyValue:StringLike': {'cognito-identity.amazonaws.com:amr': 'unauthenticated' },
});
python
principal = iam.WebIdentityPrincipal("cognito-identity.amazonaws.com", {
    "StringEquals": {"cognito-identity.amazonaws.com:aud": "us-east-2:12345678-abcd-abcd-abcd-123456"},
    "ForAnyValue:StringLike": {"cognito-identity.amazonaws.com:amr": "unauthenticated"}
})
java
WebIdentityPrincipal principal = new WebIdentityPrincipal("cognito-identity.amazonaws.com", Map.of(
        "StringEquals", Map.of("cognito-identity.amazonaws.com:aud", "us-east-2:12345678-abcd-abcd-abcd-123456"),
        "ForAnyValue:StringLike", Map.of("cognito-identity.amazonaws.com:amr", "unauthenticated")));
csharp
var principal = new WebIdentityPrincipal("cognito-identity.amazonaws.com", new Dictionary<string, object> {
    { "StringEquals", new Dictionary<string, string> { { "cognito-identity.amazonaws.com:aud", "us-east-2:12345678-abcd-abcd-abcd-123456" } } },
    { "ForAnyValue:StringLike", new Dictionary<string, string> { { "cognito-identity.amazonaws.com:amr", "unauthenticated" } } }
});
go
principal := iam.NewWebIdentityPrincipal(jsii.String("cognito-identity.amazonaws.com"), map[string]interface{}{
	"StringEquals": map[string]*string{
		"cognito-identity.amazonaws.com:aud": jsii.String("us-east-2:12345678-abcd-abcd-abcd-123456"),
	},
	"ForAnyValue:StringLike": map[string]*string{
		"cognito-identity.amazonaws.com:amr": jsii.String("unauthenticated"),
	},
})

If your identity provider is configured to assume a Role with session tags, you need to call .withSessionTags() to add the required permissions to the Role's policy document:

ts
new iam.Role(this, 'Role', {
  assumedBy: new iam.WebIdentityPrincipal('cognito-identity.amazonaws.com', {
    'StringEquals': {
      'cognito-identity.amazonaws.com:aud': 'us-east-2:12345678-abcd-abcd-abcd-123456',
     },
    'ForAnyValue:StringLike': {
      'cognito-identity.amazonaws.com:amr': 'unauthenticated',
    },
  }).withSessionTags(),
});
python
iam.Role(self, "Role",
    assumed_by=iam.WebIdentityPrincipal("cognito-identity.amazonaws.com", {
        "StringEquals": {
            "cognito-identity.amazonaws.com:aud": "us-east-2:12345678-abcd-abcd-abcd-123456"
        },
        "ForAnyValue:StringLike": {
            "cognito-identity.amazonaws.com:amr": "unauthenticated"
        }
    }).with_session_tags()
)
java
Role.Builder.create(this, "Role")
        .assumedBy(new WebIdentityPrincipal("cognito-identity.amazonaws.com", Map.of(
                "StringEquals", Map.of(
                        "cognito-identity.amazonaws.com:aud", "us-east-2:12345678-abcd-abcd-abcd-123456"),
                "ForAnyValue:StringLike", Map.of(
                        "cognito-identity.amazonaws.com:amr", "unauthenticated"))).withSessionTags())
        .build();
csharp
new Role(this, "Role", new RoleProps {
    AssumedBy = new WebIdentityPrincipal("cognito-identity.amazonaws.com", new Dictionary<string, object> {
        { "StringEquals", new Dictionary<string, string> {
            { "cognito-identity.amazonaws.com:aud", "us-east-2:12345678-abcd-abcd-abcd-123456" }
        } },
        { "ForAnyValue:StringLike", new Dictionary<string, string> {
            { "cognito-identity.amazonaws.com:amr", "unauthenticated" }
        } }
    }).WithSessionTags()
});
go
iam.NewRole(this, jsii.String("Role"), &RoleProps{
	AssumedBy: iam.NewWebIdentityPrincipal(jsii.String("cognito-identity.amazonaws.com"), map[string]interface{}{
		"StringEquals": map[string]*string{
			"cognito-identity.amazonaws.com:aud": jsii.String("us-east-2:12345678-abcd-abcd-abcd-123456"),
		},
		"ForAnyValue:StringLike": map[string]*string{
			"cognito-identity.amazonaws.com:amr": jsii.String("unauthenticated"),
		},
	}).WithSessionTags(),
})

Granting a principal permission to assume a role ​

A principal can be granted permission to assume a role using assumeRole from the RoleGrants class. For convenience, an instance of this class is available via the grants attribute on the Role class.

Note that this does not apply to service principals or account principals as they must be added to the role trust policy via assumeRolePolicy.

ts
const user = new iam.User(this, 'user')
const role = new iam.Role(this, 'role', {
  assumedBy: new iam.AccountPrincipal(this.account)
});

role.grants.assumeRole(user);
python
user = iam.User(self, "user")
role = iam.Role(self, "role",
    assumed_by=iam.AccountPrincipal(self.account)
)

role.grants.assume_role(user)
java
User user = new User(this, "user");
Role role = Role.Builder.create(this, "role")
        .assumedBy(new AccountPrincipal(this.account))
        .build();

role.grants.assumeRole(user);
csharp
var user = new User(this, "user");
var role = new Role(this, "role", new RoleProps {
    AssumedBy = new AccountPrincipal(Account)
});

role.Grants.AssumeRole(user);
go
user := iam.NewUser(this, jsii.String("user"))
role := iam.NewRole(this, jsii.String("role"), &RoleProps{
	AssumedBy: iam.NewAccountPrincipal(this.Account),
})

role.Grants.AssumeRole(user)

Granting service and account principals permission to assume a role ​

Service principals and account principals can be granted permission to assume a role using assumeRolePolicy which modifies the role trust policy.

ts
const role = new iam.Role(this, 'role', {
  assumedBy: new iam.AccountPrincipal(this.account),
});

role.assumeRolePolicy?.addStatements(new iam.PolicyStatement({
  actions: ['sts:AssumeRole'],
  principals: [
    new iam.AccountPrincipal('123456789'),
    new iam.ServicePrincipal('beep-boop.amazonaws.com')
    ],
}));
python
role = iam.Role(self, "role",
    assumed_by=iam.AccountPrincipal(self.account)
)

role.assume_role_policy.add_statements(iam.PolicyStatement(
    actions=["sts:AssumeRole"],
    principals=[
        iam.AccountPrincipal("123456789"),
        iam.ServicePrincipal("beep-boop.amazonaws.com")
    ]
))
java
Role role = Role.Builder.create(this, "role")
        .assumedBy(new AccountPrincipal(this.account))
        .build();

role.assumeRolePolicy.addStatements(PolicyStatement.Builder.create()
        .actions(List.of("sts:AssumeRole"))
        .principals(List.of(
            new AccountPrincipal("123456789"),
            new ServicePrincipal("beep-boop.amazonaws.com")))
        .build());
csharp
var role = new Role(this, "role", new RoleProps {
    AssumedBy = new AccountPrincipal(Account)
});

role.AssumeRolePolicy.AddStatements(new PolicyStatement(new PolicyStatementProps {
    Actions = new [] { "sts:AssumeRole" },
    Principals = new [] {
        new AccountPrincipal("123456789"),
        new ServicePrincipal("beep-boop.amazonaws.com") }
}));
go
role := iam.NewRole(this, jsii.String("role"), &RoleProps{
	AssumedBy: iam.NewAccountPrincipal(this.Account),
})

role.AssumeRolePolicy.AddStatements(iam.NewPolicyStatement(&PolicyStatementProps{
	Actions: []*string{
		jsii.String("sts:AssumeRole"),
	},
	Principals: []IPrincipal{
		iam.NewAccountPrincipal(jsii.String("123456789")),
		iam.NewServicePrincipal(jsii.String("beep-boop.amazonaws.com")),
	},
}))

Fixing the synthesized service principle for services that do not follow the IAM Pattern ​

In some cases, certain AWS services may not use the standard <service>.amazonaws.com pattern for their service principals. For these services, you can define the ServicePrincipal as following where the provided service principle name will be used as is without any changing.

ts
    const sp = iam.ServicePrincipal.fromStaticServicePrincipleName('elasticmapreduce.amazonaws.com.cn');
python
sp = iam.ServicePrincipal.from_static_service_principle_name("elasticmapreduce.amazonaws.com.cn")
java
ServicePrincipal sp = ServicePrincipal.fromStaticServicePrincipleName("elasticmapreduce.amazonaws.com.cn");
csharp
var sp = ServicePrincipal.FromStaticServicePrincipleName("elasticmapreduce.amazonaws.com.cn");
go
sp := iam.ServicePrincipal_FromStaticServicePrincipleName(jsii.String("elasticmapreduce.amazonaws.com.cn"))

This principle can use as normal in defining any role, for example:

ts
const emrServiceRole = new iam.Role(this, 'EMRServiceRole', {
    assumedBy: iam.ServicePrincipal.fromStaticServicePrincipleName('elasticmapreduce.amazonaws.com.cn'),
    managedPolicies: [
        iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonElasticMapReduceRole'),
    ],
});
python
emr_service_role = iam.Role(self, "EMRServiceRole",
    assumed_by=iam.ServicePrincipal.from_static_service_principle_name("elasticmapreduce.amazonaws.com.cn"),
    managed_policies=[
        iam.ManagedPolicy.from_aws_managed_policy_name("service-role/AmazonElasticMapReduceRole")
    ]
)
java
Role emrServiceRole = Role.Builder.create(this, "EMRServiceRole")
        .assumedBy(ServicePrincipal.fromStaticServicePrincipleName("elasticmapreduce.amazonaws.com.cn"))
        .managedPolicies(List.of(ManagedPolicy.fromAwsManagedPolicyName("service-role/AmazonElasticMapReduceRole")))
        .build();
csharp
var emrServiceRole = new Role(this, "EMRServiceRole", new RoleProps {
    AssumedBy = ServicePrincipal.FromStaticServicePrincipleName("elasticmapreduce.amazonaws.com.cn"),
    ManagedPolicies = new [] { ManagedPolicy.FromAwsManagedPolicyName("service-role/AmazonElasticMapReduceRole") }
});
go
emrServiceRole := iam.NewRole(this, jsii.String("EMRServiceRole"), &RoleProps{
	AssumedBy: iam.ServicePrincipal_FromStaticServicePrincipleName(jsii.String("elasticmapreduce.amazonaws.com.cn")),
	ManagedPolicies: []IManagedPolicy{
		iam.ManagedPolicy_FromAwsManagedPolicyName(jsii.String("service-role/AmazonElasticMapReduceRole")),
	},
})

Parsing JSON Policy Documents ​

The PolicyDocument.fromJson and PolicyStatement.fromJson static methods can be used to parse JSON objects. For example:

ts
const policyDocument = {
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "FirstStatement",
      "Effect": "Allow",
      "Action": ["iam:ChangePassword"],
      "Resource": ["*"],
    },
    {
      "Sid": "SecondStatement",
      "Effect": "Allow",
      "Action": ["s3:ListAllMyBuckets"],
      "Resource": ["*"],
    },
    {
      "Sid": "ThirdStatement",
      "Effect": "Allow",
      "Action": [
        "s3:List*",
        "s3:Get*",
      ],
      "Resource": [
        "arn:aws:s3:::confidential-data",
        "arn:aws:s3:::confidential-data/*",
      ],
      "Condition": {"Bool": {"aws:MultiFactorAuthPresent": "true"}},
    },
  ],
};

const customPolicyDocument = iam.PolicyDocument.fromJson(policyDocument);

// You can pass this document as an initial document to a ManagedPolicy
// or inline Policy.
const newManagedPolicy = new iam.ManagedPolicy(this, 'MyNewManagedPolicy', {
  document: customPolicyDocument,
});
const newPolicy = new iam.Policy(this, 'MyNewPolicy', {
  document: customPolicyDocument,
});
python
policy_document = {
    "Version": "2012-10-17",
    "Statement": [{
        "Sid": "FirstStatement",
        "Effect": "Allow",
        "Action": ["iam:ChangePassword"],
        "Resource": ["*"]
    }, {
        "Sid": "SecondStatement",
        "Effect": "Allow",
        "Action": ["s3:ListAllMyBuckets"],
        "Resource": ["*"]
    }, {
        "Sid": "ThirdStatement",
        "Effect": "Allow",
        "Action": ["s3:List*", "s3:Get*"
        ],
        "Resource": ["arn:aws:s3:::confidential-data", "arn:aws:s3:::confidential-data/*"
        ],
        "Condition": {"Bool": {"aws:multi_factor_auth_present": "true"}}
    }
    ]
}

custom_policy_document = iam.PolicyDocument.from_json(policy_document)

# You can pass this document as an initial document to a ManagedPolicy
# or inline Policy.
new_managed_policy = iam.ManagedPolicy(self, "MyNewManagedPolicy",
    document=custom_policy_document
)
new_policy = iam.Policy(self, "MyNewPolicy",
    document=custom_policy_document
)
java
Map<String, Object> policyDocument = Map.of(
        "Version", "2012-10-17",
        "Statement", List.of(Map.of(
                "Sid", "FirstStatement",
                "Effect", "Allow",
                "Action", List.of("iam:ChangePassword"),
                "Resource", List.of("*")), Map.of(
                "Sid", "SecondStatement",
                "Effect", "Allow",
                "Action", List.of("s3:ListAllMyBuckets"),
                "Resource", List.of("*")), Map.of(
                "Sid", "ThirdStatement",
                "Effect", "Allow",
                "Action", List.of("s3:List*", "s3:Get*"),
                "Resource", List.of("arn:aws:s3:::confidential-data", "arn:aws:s3:::confidential-data/*"),
                "Condition", Map.of("Bool", Map.of("aws:MultiFactorAuthPresent", "true")))));

PolicyDocument customPolicyDocument = PolicyDocument.fromJson(policyDocument);

// You can pass this document as an initial document to a ManagedPolicy
// or inline Policy.
ManagedPolicy newManagedPolicy = ManagedPolicy.Builder.create(this, "MyNewManagedPolicy")
        .document(customPolicyDocument)
        .build();
Policy newPolicy = Policy.Builder.create(this, "MyNewPolicy")
        .document(customPolicyDocument)
        .build();
csharp
IDictionary<string, object> policyDocument = new Dictionary<string, object> {
    { "Version", "2012-10-17" },
    { "Statement", new [] { new Dictionary<string, object> {
        { "Sid", "FirstStatement" },
        { "Effect", "Allow" },
        { "Action", new [] { "iam:ChangePassword" } },
        { "Resource", new [] { "*" } }
    }, new Dictionary<string, object> {
        { "Sid", "SecondStatement" },
        { "Effect", "Allow" },
        { "Action", new [] { "s3:ListAllMyBuckets" } },
        { "Resource", new [] { "*" } }
    }, new Dictionary<string, object> {
        { "Sid", "ThirdStatement" },
        { "Effect", "Allow" },
        { "Action", new [] { "s3:List*", "s3:Get*" } },
        { "Resource", new [] { "arn:aws:s3:::confidential-data", "arn:aws:s3:::confidential-data/*" } },
        { "Condition", new Dictionary<string, IDictionary<string, string>> { { "Bool", new Dictionary<string, string> { { "aws:MultiFactorAuthPresent", "true" } } } } }
    } } }
};

var customPolicyDocument = PolicyDocument.FromJson(policyDocument);

// You can pass this document as an initial document to a ManagedPolicy
// or inline Policy.
var newManagedPolicy = new ManagedPolicy(this, "MyNewManagedPolicy", new ManagedPolicyProps {
    Document = customPolicyDocument
});
var newPolicy = new Policy(this, "MyNewPolicy", new PolicyProps {
    Document = customPolicyDocument
});
go
policyDocument := map[string]interface{}{
	"Version": jsii.String("2012-10-17"),
	"Statement": []interface{}{
		map[string]interface{}{
			"Sid": jsii.String("FirstStatement"),
			"Effect": jsii.String("Allow"),
			"Action": []*string{
				jsii.String("iam:ChangePassword"),
			},
			"Resource": []*string{
				jsii.String("*"),
			},
		},
		map[string]interface{}{
			"Sid": jsii.String("SecondStatement"),
			"Effect": jsii.String("Allow"),
			"Action": []*string{
				jsii.String("s3:ListAllMyBuckets"),
			},
			"Resource": []*string{
				jsii.String("*"),
			},
		},
		map[string]interface{}{
			"Sid": jsii.String("ThirdStatement"),
			"Effect": jsii.String("Allow"),
			"Action": []*string{
				jsii.String("s3:List*"),
				jsii.String("s3:Get*"),
			},
			"Resource": []*string{
				jsii.String("arn:aws:s3:::confidential-data"),
				jsii.String("arn:aws:s3:::confidential-data/*"),
			},
			"Condition": map[string]map[string]*string{
				"Bool": map[string]*string{
					"aws:MultiFactorAuthPresent": jsii.String("true"),
				},
			},
		},
	},
}

customPolicyDocument := iam.PolicyDocument_FromJson(policyDocument)

// You can pass this document as an initial document to a ManagedPolicy
// or inline Policy.
newManagedPolicy := iam.NewManagedPolicy(this, jsii.String("MyNewManagedPolicy"), &ManagedPolicyProps{
	Document: customPolicyDocument,
})
newPolicy := iam.NewPolicy(this, jsii.String("MyNewPolicy"), &PolicyProps{
	Document: customPolicyDocument,
})

Identity Policy Statement SID Validation ​

The Sid (statement ID) element in IAM identity policies must be alphanumeric (A-Z, a-z, 0-9) according to AWS IAM requirements. CDK validates identity policy SIDs at synthesis time.

ts
// This will throw an error when used in an identity policy
new iam.PolicyStatement({
  sid: 'Allow access for S3.',  // Invalid: contains spaces and period
  actions: ['s3:GetObject'],
  resources: ['*'],
});

// Valid SID - alphanumeric only
new iam.PolicyStatement({
  sid: 'AllowAccessForS3',  // Valid: alphanumeric only
  actions: ['s3:GetObject'],
  resources: ['*'],
});
python
# This will throw an error when used in an identity policy
iam.PolicyStatement(
    sid="Allow access for S3.",  # Invalid: contains spaces and period
    actions=["s3:GetObject"],
    resources=["*"]
)

# Valid SID - alphanumeric only
iam.PolicyStatement(
    sid="AllowAccessForS3",  # Valid: alphanumeric only
    actions=["s3:GetObject"],
    resources=["*"]
)
java
// This will throw an error when used in an identity policy
// This will throw an error when used in an identity policy
PolicyStatement.Builder.create()
        .sid("Allow access for S3.") // Invalid: contains spaces and period
        .actions(List.of("s3:GetObject"))
        .resources(List.of("*"))
        .build();

// Valid SID - alphanumeric only
// Valid SID - alphanumeric only
PolicyStatement.Builder.create()
        .sid("AllowAccessForS3") // Valid: alphanumeric only
        .actions(List.of("s3:GetObject"))
        .resources(List.of("*"))
        .build();
csharp
// This will throw an error when used in an identity policy
// This will throw an error when used in an identity policy
new PolicyStatement(new PolicyStatementProps {
    Sid = "Allow access for S3.",  // Invalid: contains spaces and period
    Actions = new [] { "s3:GetObject" },
    Resources = new [] { "*" }
});

// Valid SID - alphanumeric only
// Valid SID - alphanumeric only
new PolicyStatement(new PolicyStatementProps {
    Sid = "AllowAccessForS3",  // Valid: alphanumeric only
    Actions = new [] { "s3:GetObject" },
    Resources = new [] { "*" }
});
go
// This will throw an error when used in an identity policy
// This will throw an error when used in an identity policy
iam.NewPolicyStatement(&PolicyStatementProps{
	Sid: jsii.String("Allow access for S3."),
	 // Invalid: contains spaces and period
	Actions: []*string{
		jsii.String("s3:GetObject"),
	},
	Resources: []*string{
		jsii.String("*"),
	},
})

// Valid SID - alphanumeric only
// Valid SID - alphanumeric only
iam.NewPolicyStatement(&PolicyStatementProps{
	Sid: jsii.String("AllowAccessForS3"),
	 // Valid: alphanumeric only
	Actions: []*string{
		jsii.String("s3:GetObject"),
	},
	Resources: []*string{
		jsii.String("*"),
	},
})

This validation helps catch SID errors early in development rather than at deployment time.

Permissions Boundaries ​

Permissions Boundaries can be used as a mechanism to prevent privilege escalation by creating new Roles. Permissions Boundaries are a Managed Policy, attached to Roles or Users, that represent the maximum set of permissions they can have. The effective set of permissions of a Role (or User) will be the intersection of the Identity Policy and the Permissions Boundary attached to the Role (or User). Permissions Boundaries are typically created by account Administrators, and their use on newly created Roles will be enforced by IAM policies.

Bootstrap Permissions Boundary ​

If a permissions boundary has been enforced as part of CDK bootstrap, all IAM Roles and Users that are created as part of the CDK application must be created with the permissions boundary attached. The most common scenario will be to apply the enforced permissions boundary to the entire CDK app. This can be done either by adding the value to cdk.json or directly in the App constructor.

For example if your organization has created and is enforcing a permissions boundary with the name cdk-${Qualifier}-PermissionsBoundary

json
{
  "context": {
     "@aws-cdk/core:permissionsBoundary": {
	   "name": "cdk-${Qualifier}-PermissionsBoundary"
	 }
  }
}

OR

ts
new App({
  context: {
    [PERMISSIONS_BOUNDARY_CONTEXT_KEY]: {
      name: 'cdk-${Qualifier}-PermissionsBoundary',
    },
  },
});
python
App(
    context={
        "PERMISSIONS_BOUNDARY_CONTEXT_KEY": {
            "name": "cdk-${Qualifier}-PermissionsBoundary"
        }
    }
)
java
App.Builder.create()
        .context(Map.of(
                PERMISSIONS_BOUNDARY_CONTEXT_KEY, Map.of(
                        "name", "cdk-${Qualifier}-PermissionsBoundary")))
        .build();
csharp
new App(new AppProps {
    Context = new Dictionary<string, object> {
        { PERMISSIONS_BOUNDARY_CONTEXT_KEY, new Dictionary<string, string> {
            { "name", "cdk-${Qualifier}-PermissionsBoundary" }
        } }
    }
});
go
awscdk.NewApp(&AppProps{
	Context: map[string]interface{}{
		awscdk.PERMISSIONS_BOUNDARY_CONTEXT_KEY: map[string]*string{
			"name": jsii.String("cdk-${Qualifier}-PermissionsBoundary"),
		},
	},
})

Another scenario might be if your organization enforces different permissions boundaries for different environments. For example your CDK application may have

  • DevStage that deploys to a personal dev environment where you have elevated privileges
  • BetaStage that deploys to a beta environment which and has a relaxed permissions boundary
  • GammaStage that deploys to a gamma environment which has the prod permissions boundary
  • ProdStage that deploys to the prod environment and has the prod permissions boundary
ts
declare const app: App;

new Stage(app, 'DevStage');

new Stage(app, 'BetaStage', {
  permissionsBoundary: PermissionsBoundary.fromName('beta-permissions-boundary'),
});

new Stage(app, 'GammaStage', {
  permissionsBoundary: PermissionsBoundary.fromName('prod-permissions-boundary'),
});

new Stage(app, 'ProdStage', {
  permissionsBoundary: PermissionsBoundary.fromName('prod-permissions-boundary'),
});
python
# app: App


Stage(app, "DevStage")

Stage(app, "BetaStage",
    permissions_boundary=PermissionsBoundary.from_name("beta-permissions-boundary")
)

Stage(app, "GammaStage",
    permissions_boundary=PermissionsBoundary.from_name("prod-permissions-boundary")
)

Stage(app, "ProdStage",
    permissions_boundary=PermissionsBoundary.from_name("prod-permissions-boundary")
)
java
App app;


new Stage(app, "DevStage");

Stage.Builder.create(app, "BetaStage")
        .permissionsBoundary(PermissionsBoundary.fromName("beta-permissions-boundary"))
        .build();

Stage.Builder.create(app, "GammaStage")
        .permissionsBoundary(PermissionsBoundary.fromName("prod-permissions-boundary"))
        .build();

Stage.Builder.create(app, "ProdStage")
        .permissionsBoundary(PermissionsBoundary.fromName("prod-permissions-boundary"))
        .build();
csharp
App app;


new Stage(app, "DevStage");

new Stage(app, "BetaStage", new StageProps {
    PermissionsBoundary = PermissionsBoundary.FromName("beta-permissions-boundary")
});

new Stage(app, "GammaStage", new StageProps {
    PermissionsBoundary = PermissionsBoundary.FromName("prod-permissions-boundary")
});

new Stage(app, "ProdStage", new StageProps {
    PermissionsBoundary = PermissionsBoundary.FromName("prod-permissions-boundary")
});
go
var app App


awscdk.NewStage(app, jsii.String("DevStage"))

awscdk.NewStage(app, jsii.String("BetaStage"), &StageProps{
	PermissionsBoundary: awscdk.PermissionsBoundary_FromName(jsii.String("beta-permissions-boundary")),
})

awscdk.NewStage(app, jsii.String("GammaStage"), &StageProps{
	PermissionsBoundary: awscdk.PermissionsBoundary_*FromName(jsii.String("prod-permissions-boundary")),
})

awscdk.NewStage(app, jsii.String("ProdStage"), &StageProps{
	PermissionsBoundary: awscdk.PermissionsBoundary_*FromName(jsii.String("prod-permissions-boundary")),
})

The provided name can include placeholders for the partition, region, qualifier, and account These placeholders will be replaced with the actual values if available. This requires that the Stack has the environment specified, it does not work with environment.

  • '${AWS::Partition}'
  • '${AWS::Region}'
  • '${AWS::AccountId}'
  • '${Qualifier}'
ts
declare const app: App;

const prodStage = new Stage(app, 'ProdStage', {
  permissionsBoundary: PermissionsBoundary.fromName('cdk-${Qualifier}-PermissionsBoundary-${AWS::AccountId}-${AWS::Region}'),
});

new Stack(prodStage, 'ProdStack', {
  synthesizer: new DefaultStackSynthesizer({
    qualifier: 'custom',
  }),
});
python
# app: App


prod_stage = Stage(app, "ProdStage",
    permissions_boundary=PermissionsBoundary.from_name("cdk-${Qualifier}-PermissionsBoundary-${AWS::AccountId}-${AWS::Region}")
)

Stack(prod_stage, "ProdStack",
    synthesizer=DefaultStackSynthesizer(
        qualifier="custom"
    )
)
java
App app;


Stage prodStage = Stage.Builder.create(app, "ProdStage")
        .permissionsBoundary(PermissionsBoundary.fromName("cdk-${Qualifier}-PermissionsBoundary-${AWS::AccountId}-${AWS::Region}"))
        .build();

Stack.Builder.create(prodStage, "ProdStack")
        .synthesizer(DefaultStackSynthesizer.Builder.create()
                .qualifier("custom")
                .build())
        .build();
csharp
App app;


var prodStage = new Stage(app, "ProdStage", new StageProps {
    PermissionsBoundary = PermissionsBoundary.FromName("cdk-${Qualifier}-PermissionsBoundary-${AWS::AccountId}-${AWS::Region}")
});

new Stack(prodStage, "ProdStack", new StackProps {
    Synthesizer = new DefaultStackSynthesizer(new DefaultStackSynthesizerProps {
        Qualifier = "custom"
    })
});
go
var app App


prodStage := awscdk.NewStage(app, jsii.String("ProdStage"), &StageProps{
	PermissionsBoundary: awscdk.PermissionsBoundary_FromName(jsii.String("cdk-${Qualifier}-PermissionsBoundary-${AWS::AccountId}-${AWS::Region}")),
})

awscdk.Newstack(prodStage, jsii.String("ProdStack"), &StackProps{
	Synthesizer: awscdk.NewDefaultStackSynthesizer(&DefaultStackSynthesizerProps{
		Qualifier: jsii.String("custom"),
	}),
})

For more information on configuring permissions see the Security And Safety Dev Guide

Custom Permissions Boundary ​

It is possible to attach Permissions Boundaries to all Roles created in a construct tree all at once:

ts
// This imports an existing policy.
const boundary = iam.ManagedPolicy.fromManagedPolicyArn(this, 'Boundary', 'arn:aws:iam::123456789012:policy/boundary');

// This creates a new boundary
const boundary2 = new iam.ManagedPolicy(this, 'Boundary2', {
  statements: [
    new iam.PolicyStatement({
      effect: iam.Effect.DENY,
      actions: ['iam:*'],
      resources: ['*'],
    }),
  ],
});

// Directly apply the boundary to a Role you create
declare const role: iam.Role;
iam.PermissionsBoundary.of(role).apply(boundary);

// Apply the boundary to an Role that was implicitly created for you
declare const fn: lambda.Function;
iam.PermissionsBoundary.of(fn).apply(boundary);

// Apply the boundary to all Roles in a stack
iam.PermissionsBoundary.of(this).apply(boundary);

// Remove a Permissions Boundary that is inherited, for example from the Stack level
declare const customResource: CustomResource;
iam.PermissionsBoundary.of(customResource).clear();
python
# Directly apply the boundary to a Role you create
# role: iam.Role

# Apply the boundary to an Role that was implicitly created for you
# fn: lambda.Function

# Remove a Permissions Boundary that is inherited, for example from the Stack level
# custom_resource: CustomResource
# This imports an existing policy.
boundary = iam.ManagedPolicy.from_managed_policy_arn(self, "Boundary", "arn:aws:iam::123456789012:policy/boundary")

# This creates a new boundary
boundary2 = iam.ManagedPolicy(self, "Boundary2",
    statements=[
        iam.PolicyStatement(
            effect=iam.Effect.DENY,
            actions=["iam:*"],
            resources=["*"]
        )
    ]
)
iam.PermissionsBoundary.of(role).apply(boundary)
iam.PermissionsBoundary.of(fn).apply(boundary)

# Apply the boundary to all Roles in a stack
iam.PermissionsBoundary.of(self).apply(boundary)
iam.PermissionsBoundary.of(custom_resource).clear()
java
// Directly apply the boundary to a Role you create
Role role;

// Apply the boundary to an Role that was implicitly created for you
Function fn;

// Remove a Permissions Boundary that is inherited, for example from the Stack level
CustomResource customResource;
// This imports an existing policy.
IManagedPolicy boundary = ManagedPolicy.fromManagedPolicyArn(this, "Boundary", "arn:aws:iam::123456789012:policy/boundary");

// This creates a new boundary
ManagedPolicy boundary2 = ManagedPolicy.Builder.create(this, "Boundary2")
        .statements(List.of(
            PolicyStatement.Builder.create()
                    .effect(Effect.DENY)
                    .actions(List.of("iam:*"))
                    .resources(List.of("*"))
                    .build()))
        .build();
PermissionsBoundary.of(role).apply(boundary);
PermissionsBoundary.of(fn).apply(boundary);

// Apply the boundary to all Roles in a stack
PermissionsBoundary.of(this).apply(boundary);
PermissionsBoundary.of(customResource).clear();
csharp
// Directly apply the boundary to a Role you create
Role role;

// Apply the boundary to an Role that was implicitly created for you
Function fn;

// Remove a Permissions Boundary that is inherited, for example from the Stack level
CustomResource customResource;
// This imports an existing policy.
var boundary = ManagedPolicy.FromManagedPolicyArn(this, "Boundary", "arn:aws:iam::123456789012:policy/boundary");

// This creates a new boundary
var boundary2 = new ManagedPolicy(this, "Boundary2", new ManagedPolicyProps {
    Statements = new [] {
        new PolicyStatement(new PolicyStatementProps {
            Effect = Effect.DENY,
            Actions = new [] { "iam:*" },
            Resources = new [] { "*" }
        }) }
});
PermissionsBoundary.Of(role).Apply(boundary);
PermissionsBoundary.Of(fn).Apply(boundary);

// Apply the boundary to all Roles in a stack
PermissionsBoundary.Of(this).Apply(boundary);
PermissionsBoundary.Of(customResource).Clear();
go
// Directly apply the boundary to a Role you create
var role Role

// Apply the boundary to an Role that was implicitly created for you
var fn Function

// Remove a Permissions Boundary that is inherited, for example from the Stack level
var customResource CustomResource
// This imports an existing policy.
boundary := iam.ManagedPolicy_FromManagedPolicyArn(this, jsii.String("Boundary"), jsii.String("arn:aws:iam::123456789012:policy/boundary"))

// This creates a new boundary
boundary2 := iam.NewManagedPolicy(this, jsii.String("Boundary2"), &ManagedPolicyProps{
	Statements: []PolicyStatement{
		iam.NewPolicyStatement(&PolicyStatementProps{
			Effect: iam.Effect_DENY,
			Actions: []*string{
				jsii.String("iam:*"),
			},
			Resources: []*string{
				jsii.String("*"),
			},
		}),
	},
})
iam.PermissionsBoundary_Of(role).Apply(boundary)
iam.PermissionsBoundary_Of(fn).Apply(boundary)

// Apply the boundary to all Roles in a stack
iam.PermissionsBoundary_Of(this).Apply(boundary)
iam.PermissionsBoundary_Of(customResource).Clear()

OpenID Connect Providers ​

OIDC identity providers are entities in IAM that describe an external identity provider (IdP) service that supports the OpenID Connect (OIDC) standard, such as Google or Salesforce. You use an IAM OIDC identity provider when you want to establish trust between an OIDC-compatible IdP and your AWS account. This is useful when creating a mobile app or web application that requires access to AWS resources, but you don't want to create custom sign-in code or manage your own user identities. For more information about this scenario, see About Web Identity Federation and the relevant documentation in the Amazon Cognito Identity Pools Developer Guide.

The following examples defines an OpenID Connect provider. Two client IDs (audiences) are will be able to send authentication requests to <https://openid/connect>.

The older OpenIdConnectProvider is still supported, but for new stacks, it is recommended to use the new OidcProviderNative which uses the native CloudFormation resource AWS::IAM::OIDCProvider over the old OpenIdConnectProvider which uses a custom resource. While OidcProviderNative does not provide new features compared to OpenIdConnectProvider, it offers a simpler implementation using native CloudFormation resources instead of custom resources.

ts
const nativeProvider = new iam.OidcProviderNative(this, 'MyProvider', {
  url: 'https://openid/connect',
  clientIds: [ 'myclient1', 'myclient2' ],
  thumbprints: ['aa00aa1122aa00aa1122aa00aa1122aa00aa1122'],
});
python
native_provider = iam.OidcProviderNative(self, "MyProvider",
    url="https://openid/connect",
    client_ids=["myclient1", "myclient2"],
    thumbprints=["aa00aa1122aa00aa1122aa00aa1122aa00aa1122"]
)
java
OidcProviderNative nativeProvider = OidcProviderNative.Builder.create(this, "MyProvider")
        .url("https://openid/connect")
        .clientIds(List.of("myclient1", "myclient2"))
        .thumbprints(List.of("aa00aa1122aa00aa1122aa00aa1122aa00aa1122"))
        .build();
csharp
var nativeProvider = new OidcProviderNative(this, "MyProvider", new OidcProviderNativeProps {
    Url = "https://openid/connect",
    ClientIds = new [] { "myclient1", "myclient2" },
    Thumbprints = new [] { "aa00aa1122aa00aa1122aa00aa1122aa00aa1122" }
});
go
nativeProvider := iam.NewOidcProviderNative(this, jsii.String("MyProvider"), &OidcProviderNativeProps{
	Url: jsii.String("https://openid/connect"),
	ClientIds: []*string{
		jsii.String("myclient1"),
		jsii.String("myclient2"),
	},
	Thumbprints: []*string{
		jsii.String("aa00aa1122aa00aa1122aa00aa1122aa00aa1122"),
	},
})

For the new OidcProviderNative, you must provide at least one thumbprint when creating an IAM OIDC provider. For example, assume that the OIDC provider is server.example.com and the provider stores its keys at https://keys.server.example.com/openid-connect. In that case, the thumbprint string would be the hex-encoded SHA-1 hash value of the certificate used by https://keys.server.example.com.

The server certificate thumbprint is the hex-encoded SHA-1 hash value of the X.509 certificate used by the domain where the OpenID Connect provider makes its keys available. It is always a 40-character string.

Typically this list includes only one entry. However, IAM lets you have up to five thumbprints for an OIDC provider. This lets you maintain multiple thumbprints if the identity provider is rotating certificates.

Obtain the thumbprint of the root certificate authority from the provider's server as described in https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc_verify-thumbprint.html

The older OpenIdConnectProvider is still supported but it is recommended to use the new OidcProviderNative instead.

ts
const provider = new iam.OpenIdConnectProvider(this, 'MyProvider', {
  url: 'https://openid/connect',
  clientIds: [ 'myclient1', 'myclient2' ],
});
python
provider = iam.OpenIdConnectProvider(self, "MyProvider",
    url="https://openid/connect",
    client_ids=["myclient1", "myclient2"]
)
java
OpenIdConnectProvider provider = OpenIdConnectProvider.Builder.create(this, "MyProvider")
        .url("https://openid/connect")
        .clientIds(List.of("myclient1", "myclient2"))
        .build();
csharp
var provider = new OpenIdConnectProvider(this, "MyProvider", new OpenIdConnectProviderProps {
    Url = "https://openid/connect",
    ClientIds = new [] { "myclient1", "myclient2" }
});
go
provider := iam.NewOpenIdConnectProvider(this, jsii.String("MyProvider"), &OpenIdConnectProviderProps{
	Url: jsii.String("https://openid/connect"),
	ClientIds: []*string{
		jsii.String("myclient1"),
		jsii.String("myclient2"),
	},
})

For the older OpenIdConnectProvider, you can specify an optional list of thumbprints. If not specified, the thumbprint of the root certificate authority (CA) will automatically be obtained from the host as described here.

By default, the custom resource enforces strict security practices by rejecting any unauthorized connections when downloading CA thumbprints from the issuer URL. If you need to connect to an unauthorized OIDC identity provider and understand the implications, you can disable this behavior by setting the feature flag IAM_OIDC_REJECT_UNAUTHORIZED_CONNECTIONS to false in your cdk.context.json or cdk.json. Visit CDK Feature Flag for more information on how to configure feature flags.

Once you define an OpenID connect provider, you can use it with AWS services that expect an IAM OIDC provider. For example, when you define an Amazon Cognito identity pool you can reference the provider's ARN as follows:

ts
import * as cognito from 'aws-cdk-lib/aws-cognito';

declare const myProvider: iam.OpenIdConnectProvider;
new cognito.CfnIdentityPool(this, 'IdentityPool', {
  openIdConnectProviderArns: [myProvider.openIdConnectProviderArn],
  // And the other properties for your identity pool
  allowUnauthenticatedIdentities: false,
});
python
import aws_cdk.aws_cognito as cognito

# my_provider: iam.OpenIdConnectProvider

cognito.CfnIdentityPool(self, "IdentityPool",
    open_id_connect_provider_arns=[my_provider.open_id_connect_provider_arn],
    # And the other properties for your identity pool
    allow_unauthenticated_identities=False
)
java
import software.amazon.awscdk.services.cognito.*;

OpenIdConnectProvider myProvider;

CfnIdentityPool.Builder.create(this, "IdentityPool")
        .openIdConnectProviderArns(List.of(myProvider.getOpenIdConnectProviderArn()))
        // And the other properties for your identity pool
        .allowUnauthenticatedIdentities(false)
        .build();
csharp
using Amazon.CDK.AWS.Cognito;

OpenIdConnectProvider myProvider;

new CfnIdentityPool(this, "IdentityPool", new CfnIdentityPoolProps {
    OpenIdConnectProviderArns = new [] { myProvider.OpenIdConnectProviderArn },
    // And the other properties for your identity pool
    AllowUnauthenticatedIdentities = false
});
go
import cognito "github.com/aws/aws-cdk-go/awscdk"

var myProvider OpenIdConnectProvider

cognito.NewCfnIdentityPool(this, jsii.String("IdentityPool"), &CfnIdentityPoolProps{
	OpenIdConnectProviderArns: []interface{}{
		myProvider.openIdConnectProviderArn,
	},
	// And the other properties for your identity pool
	AllowUnauthenticatedIdentities: jsii.Boolean(false),
})

The OpenIdConnectPrincipal class can be used as a principal used with a OpenIdConnectProvider, for example:

ts
const provider = new iam.OpenIdConnectProvider(this, 'MyProvider', {
  url: 'https://openid/connect',
  clientIds: [ 'myclient1', 'myclient2' ],
});
const principal = new iam.OpenIdConnectPrincipal(provider);
python
provider = iam.OpenIdConnectProvider(self, "MyProvider",
    url="https://openid/connect",
    client_ids=["myclient1", "myclient2"]
)
principal = iam.OpenIdConnectPrincipal(provider)
java
OpenIdConnectProvider provider = OpenIdConnectProvider.Builder.create(this, "MyProvider")
        .url("https://openid/connect")
        .clientIds(List.of("myclient1", "myclient2"))
        .build();
OpenIdConnectPrincipal principal = new OpenIdConnectPrincipal(provider);
csharp
var provider = new OpenIdConnectProvider(this, "MyProvider", new OpenIdConnectProviderProps {
    Url = "https://openid/connect",
    ClientIds = new [] { "myclient1", "myclient2" }
});
var principal = new OpenIdConnectPrincipal(provider);
go
provider := iam.NewOpenIdConnectProvider(this, jsii.String("MyProvider"), &OpenIdConnectProviderProps{
	Url: jsii.String("https://openid/connect"),
	ClientIds: []*string{
		jsii.String("myclient1"),
		jsii.String("myclient2"),
	},
})
principal := iam.NewOpenIdConnectPrincipal(provider)

SAML provider ​

An IAM SAML 2.0 identity provider is an entity in IAM that describes an external identity provider (IdP) service that supports the SAML 2.0 (Security Assertion Markup Language 2.0) standard. You use an IAM identity provider when you want to establish trust between a SAML-compatible IdP such as Shibboleth or Active Directory Federation Services and AWS, so that users in your organization can access AWS resources. IAM SAML identity providers are used as principals in an IAM trust policy.

ts
new iam.SamlProvider(this, 'Provider', {
  metadataDocument: iam.SamlMetadataDocument.fromFile('/path/to/saml-metadata-document.xml'),
});
python
iam.SamlProvider(self, "Provider",
    metadata_document=iam.SamlMetadataDocument.from_file("/path/to/saml-metadata-document.xml")
)
java
SamlProvider.Builder.create(this, "Provider")
        .metadataDocument(SamlMetadataDocument.fromFile("/path/to/saml-metadata-document.xml"))
        .build();
csharp
new SamlProvider(this, "Provider", new SamlProviderProps {
    MetadataDocument = SamlMetadataDocument.FromFile("/path/to/saml-metadata-document.xml")
});
go
iam.NewSamlProvider(this, jsii.String("Provider"), &SamlProviderProps{
	MetadataDocument: iam.SamlMetadataDocument_FromFile(jsii.String("/path/to/saml-metadata-document.xml")),
})

The SamlPrincipal class can be used as a principal with a SamlProvider:

ts
const provider = new iam.SamlProvider(this, 'Provider', {
  metadataDocument: iam.SamlMetadataDocument.fromFile('/path/to/saml-metadata-document.xml'),
});
const principal = new iam.SamlPrincipal(provider, {
  StringEquals: {
    'SAML:iss': 'issuer',
  },
});
python
provider = iam.SamlProvider(self, "Provider",
    metadata_document=iam.SamlMetadataDocument.from_file("/path/to/saml-metadata-document.xml")
)
principal = iam.SamlPrincipal(provider, {
    "StringEquals": {
        "SAML:iss": "issuer"
    }
})
java
SamlProvider provider = SamlProvider.Builder.create(this, "Provider")
        .metadataDocument(SamlMetadataDocument.fromFile("/path/to/saml-metadata-document.xml"))
        .build();
SamlPrincipal principal = new SamlPrincipal(provider, Map.of(
        "StringEquals", Map.of(
                "SAML:iss", "issuer")));
csharp
var provider = new SamlProvider(this, "Provider", new SamlProviderProps {
    MetadataDocument = SamlMetadataDocument.FromFile("/path/to/saml-metadata-document.xml")
});
var principal = new SamlPrincipal(provider, new Dictionary<string, object> {
    { "StringEquals", new Dictionary<string, string> {
        { "SAML:iss", "issuer" }
    } }
});
go
provider := iam.NewSamlProvider(this, jsii.String("Provider"), &SamlProviderProps{
	MetadataDocument: iam.SamlMetadataDocument_FromFile(jsii.String("/path/to/saml-metadata-document.xml")),
})
principal := iam.NewSamlPrincipal(provider, map[string]interface{}{
	"StringEquals": map[string]*string{
		"SAML:iss": jsii.String("issuer"),
	},
})

When creating a role for programmatic and AWS Management Console access, use the SamlConsolePrincipal class:

ts
const provider = new iam.SamlProvider(this, 'Provider', {
  metadataDocument: iam.SamlMetadataDocument.fromFile('/path/to/saml-metadata-document.xml'),
});
new iam.Role(this, 'Role', {
  assumedBy: new iam.SamlConsolePrincipal(provider),
});
python
provider = iam.SamlProvider(self, "Provider",
    metadata_document=iam.SamlMetadataDocument.from_file("/path/to/saml-metadata-document.xml")
)
iam.Role(self, "Role",
    assumed_by=iam.SamlConsolePrincipal(provider)
)
java
SamlProvider provider = SamlProvider.Builder.create(this, "Provider")
        .metadataDocument(SamlMetadataDocument.fromFile("/path/to/saml-metadata-document.xml"))
        .build();
Role.Builder.create(this, "Role")
        .assumedBy(new SamlConsolePrincipal(provider))
        .build();
csharp
var provider = new SamlProvider(this, "Provider", new SamlProviderProps {
    MetadataDocument = SamlMetadataDocument.FromFile("/path/to/saml-metadata-document.xml")
});
new Role(this, "Role", new RoleProps {
    AssumedBy = new SamlConsolePrincipal(provider)
});
go
provider := iam.NewSamlProvider(this, jsii.String("Provider"), &SamlProviderProps{
	MetadataDocument: iam.SamlMetadataDocument_FromFile(jsii.String("/path/to/saml-metadata-document.xml")),
})
iam.NewRole(this, jsii.String("Role"), &RoleProps{
	AssumedBy: iam.NewSamlConsolePrincipal(provider),
})

Users ​

IAM manages users for your AWS account. To create a new user:

ts
const user = new iam.User(this, 'MyUser');
python
user = iam.User(self, "MyUser")
java
User user = new User(this, "MyUser");
csharp
var user = new User(this, "MyUser");
go
user := iam.NewUser(this, jsii.String("MyUser"))

To import an existing user by name with path:

ts
const user = iam.User.fromUserName(this, 'MyImportedUserByName', 'johnsmith');
python
user = iam.User.from_user_name(self, "MyImportedUserByName", "johnsmith")
java
IUser user = User.fromUserName(this, "MyImportedUserByName", "johnsmith");
csharp
var user = User.FromUserName(this, "MyImportedUserByName", "johnsmith");
go
user := iam.User_FromUserName(this, jsii.String("MyImportedUserByName"), jsii.String("johnsmith"))

To import an existing user by ARN:

ts
const user = iam.User.fromUserArn(this, 'MyImportedUserByArn', 'arn:aws:iam::123456789012:user/johnsmith');
python
user = iam.User.from_user_arn(self, "MyImportedUserByArn", "arn:aws:iam::123456789012:user/johnsmith")
java
IUser user = User.fromUserArn(this, "MyImportedUserByArn", "arn:aws:iam::123456789012:user/johnsmith");
csharp
var user = User.FromUserArn(this, "MyImportedUserByArn", "arn:aws:iam::123456789012:user/johnsmith");
go
user := iam.User_FromUserArn(this, jsii.String("MyImportedUserByArn"), jsii.String("arn:aws:iam::123456789012:user/johnsmith"))

To import an existing user by attributes:

ts
const user = iam.User.fromUserAttributes(this, 'MyImportedUserByAttributes', {
  userArn: 'arn:aws:iam::123456789012:user/johnsmith',
});
python
user = iam.User.from_user_attributes(self, "MyImportedUserByAttributes",
    user_arn="arn:aws:iam::123456789012:user/johnsmith"
)
java
IUser user = User.fromUserAttributes(this, "MyImportedUserByAttributes", UserAttributes.builder()
        .userArn("arn:aws:iam::123456789012:user/johnsmith")
        .build());
csharp
var user = User.FromUserAttributes(this, "MyImportedUserByAttributes", new UserAttributes {
    UserArn = "arn:aws:iam::123456789012:user/johnsmith"
});
go
user := iam.User_FromUserAttributes(this, jsii.String("MyImportedUserByAttributes"), &UserAttributes{
	UserArn: jsii.String("arn:aws:iam::123456789012:user/johnsmith"),
})

Access Keys ​

The ability for a user to make API calls via the CLI or an SDK is enabled by the user having an access key pair. To create an access key:

ts
const user = new iam.User(this, 'MyUser');
const accessKey = new iam.AccessKey(this, 'MyAccessKey', { user: user });
python
user = iam.User(self, "MyUser")
access_key = iam.AccessKey(self, "MyAccessKey", user=user)
java
User user = new User(this, "MyUser");
AccessKey accessKey = AccessKey.Builder.create(this, "MyAccessKey").user(user).build();
csharp
var user = new User(this, "MyUser");
var accessKey = new AccessKey(this, "MyAccessKey", new AccessKeyProps { User = user });
go
user := iam.NewUser(this, jsii.String("MyUser"))
accessKey := iam.NewAccessKey(this, jsii.String("MyAccessKey"), &AccessKeyProps{
	User: user,
})

You can force CloudFormation to rotate the access key by providing a monotonically increasing serial property. Simply provide a higher serial value than any number used previously:

ts
const user = new iam.User(this, 'MyUser');
const accessKey = new iam.AccessKey(this, 'MyAccessKey', { user: user, serial: 1 });
python
user = iam.User(self, "MyUser")
access_key = iam.AccessKey(self, "MyAccessKey", user=user, serial=1)
java
User user = new User(this, "MyUser");
AccessKey accessKey = AccessKey.Builder.create(this, "MyAccessKey").user(user).serial(1).build();
csharp
var user = new User(this, "MyUser");
var accessKey = new AccessKey(this, "MyAccessKey", new AccessKeyProps { User = user, Serial = 1 });
go
user := iam.NewUser(this, jsii.String("MyUser"))
accessKey := iam.NewAccessKey(this, jsii.String("MyAccessKey"), &AccessKeyProps{
	User: user,
	Serial: jsii.Number(1),
})

An access key may only be associated with a single user and cannot be "moved" between users. Changing the user associated with an access key replaces the access key (and its ID and secret value).

Groups ​

An IAM user group is a collection of IAM users. User groups let you specify permissions for multiple users.

ts
const group = new iam.Group(this, 'MyGroup');
python
group = iam.Group(self, "MyGroup")
java
Group group = new Group(this, "MyGroup");
csharp
var group = new Group(this, "MyGroup");
go
group := iam.NewGroup(this, jsii.String("MyGroup"))

To import an existing group by ARN:

ts
const group = iam.Group.fromGroupArn(this, 'MyImportedGroupByArn', 'arn:aws:iam::account-id:group/group-name');
python
group = iam.Group.from_group_arn(self, "MyImportedGroupByArn", "arn:aws:iam::account-id:group/group-name")
java
IGroup group = Group.fromGroupArn(this, "MyImportedGroupByArn", "arn:aws:iam::account-id:group/group-name");
csharp
var group = Group.FromGroupArn(this, "MyImportedGroupByArn", "arn:aws:iam::account-id:group/group-name");
go
group := iam.Group_FromGroupArn(this, jsii.String("MyImportedGroupByArn"), jsii.String("arn:aws:iam::account-id:group/group-name"))

To import an existing group by name with path:

ts
const group = iam.Group.fromGroupName(this, 'MyImportedGroupByName', 'group-name');
python
group = iam.Group.from_group_name(self, "MyImportedGroupByName", "group-name")
java
IGroup group = Group.fromGroupName(this, "MyImportedGroupByName", "group-name");
csharp
var group = Group.FromGroupName(this, "MyImportedGroupByName", "group-name");
go
group := iam.Group_FromGroupName(this, jsii.String("MyImportedGroupByName"), jsii.String("group-name"))

To add a user to a group (both for a new and imported user/group):

ts
const user = new iam.User(this, 'MyUser'); // or User.fromUserName(this, 'User', 'johnsmith');
const group = new iam.Group(this, 'MyGroup'); // or Group.fromGroupArn(this, 'Group', 'arn:aws:iam::account-id:group/group-name');

user.addToGroup(group);
// or
group.addUser(user);
python
user = iam.User(self, "MyUser") # or User.fromUserName(this, 'User', 'johnsmith');
group = iam.Group(self, "MyGroup") # or Group.fromGroupArn(this, 'Group', 'arn:aws:iam::account-id:group/group-name');

user.add_to_group(group)
# or
group.add_user(user)
java
User user = new User(this, "MyUser"); // or User.fromUserName(this, 'User', 'johnsmith');
Group group = new Group(this, "MyGroup"); // or Group.fromGroupArn(this, 'Group', 'arn:aws:iam::account-id:group/group-name');

user.addToGroup(group);
// or
group.addUser(user);
csharp
var user = new User(this, "MyUser"); // or User.fromUserName(this, 'User', 'johnsmith');
var group = new Group(this, "MyGroup"); // or Group.fromGroupArn(this, 'Group', 'arn:aws:iam::account-id:group/group-name');

user.AddToGroup(group);
// or
group.AddUser(user);
go
user := iam.NewUser(this, jsii.String("MyUser")) // or User.fromUserName(this, 'User', 'johnsmith');
group := iam.NewGroup(this, jsii.String("MyGroup")) // or Group.fromGroupArn(this, 'Group', 'arn:aws:iam::account-id:group/group-name');

user.AddToGroup(group)
// or
group.addUser(user)

Instance Profiles ​

An IAM instance profile is a container for an IAM role that you can use to pass role information to an EC2 instance when the instance starts. By default, an instance profile must be created with a role:

ts
const role = new iam.Role(this, 'Role', {
  assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'),
});

const instanceProfile = new iam.InstanceProfile(this, 'InstanceProfile', {
  role,
});
python
role = iam.Role(self, "Role",
    assumed_by=iam.ServicePrincipal("ec2.amazonaws.com")
)

instance_profile = iam.InstanceProfile(self, "InstanceProfile",
    role=role
)
java
Role role = Role.Builder.create(this, "Role")
        .assumedBy(new ServicePrincipal("ec2.amazonaws.com"))
        .build();

InstanceProfile instanceProfile = InstanceProfile.Builder.create(this, "InstanceProfile")
        .role(role)
        .build();
csharp
var role = new Role(this, "Role", new RoleProps {
    AssumedBy = new ServicePrincipal("ec2.amazonaws.com")
});

var instanceProfile = new InstanceProfile(this, "InstanceProfile", new InstanceProfileProps {
    Role = role
});
go
role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("ec2.amazonaws.com")),
})

instanceProfile := iam.NewInstanceProfile(this, jsii.String("InstanceProfile"), &InstanceProfileProps{
	Role: Role,
})

An instance profile can also optionally be created with an instance profile name and/or a path to the instance profile:

ts
const role = new iam.Role(this, 'Role', {
  assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'),
});

const instanceProfile = new iam.InstanceProfile(this, 'InstanceProfile', {
  role,
  instanceProfileName: 'MyInstanceProfile',
  path: '/sample/path/',
});
python
role = iam.Role(self, "Role",
    assumed_by=iam.ServicePrincipal("ec2.amazonaws.com")
)

instance_profile = iam.InstanceProfile(self, "InstanceProfile",
    role=role,
    instance_profile_name="MyInstanceProfile",
    path="/sample/path/"
)
java
Role role = Role.Builder.create(this, "Role")
        .assumedBy(new ServicePrincipal("ec2.amazonaws.com"))
        .build();

InstanceProfile instanceProfile = InstanceProfile.Builder.create(this, "InstanceProfile")
        .role(role)
        .instanceProfileName("MyInstanceProfile")
        .path("/sample/path/")
        .build();
csharp
var role = new Role(this, "Role", new RoleProps {
    AssumedBy = new ServicePrincipal("ec2.amazonaws.com")
});

var instanceProfile = new InstanceProfile(this, "InstanceProfile", new InstanceProfileProps {
    Role = role,
    InstanceProfileName = "MyInstanceProfile",
    Path = "/sample/path/"
});
go
role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("ec2.amazonaws.com")),
})

instanceProfile := iam.NewInstanceProfile(this, jsii.String("InstanceProfile"), &InstanceProfileProps{
	Role: Role,
	InstanceProfileName: jsii.String("MyInstanceProfile"),
	Path: jsii.String("/sample/path/"),
})

To import an existing instance profile by name:

ts
const instanceProfile = iam.InstanceProfile.fromInstanceProfileName(this, 'ImportedInstanceProfile', 'MyInstanceProfile');
python
instance_profile = iam.InstanceProfile.from_instance_profile_name(self, "ImportedInstanceProfile", "MyInstanceProfile")
java
IInstanceProfile instanceProfile = InstanceProfile.fromInstanceProfileName(this, "ImportedInstanceProfile", "MyInstanceProfile");
csharp
var instanceProfile = InstanceProfile.FromInstanceProfileName(this, "ImportedInstanceProfile", "MyInstanceProfile");
go
instanceProfile := iam.InstanceProfile_FromInstanceProfileName(this, jsii.String("ImportedInstanceProfile"), jsii.String("MyInstanceProfile"))

To import an existing instance profile by ARN:

ts
const instanceProfile = iam.InstanceProfile.fromInstanceProfileArn(this, 'ImportedInstanceProfile', 'arn:aws:iam::account-id:instance-profile/MyInstanceProfile');
python
instance_profile = iam.InstanceProfile.from_instance_profile_arn(self, "ImportedInstanceProfile", "arn:aws:iam::account-id:instance-profile/MyInstanceProfile")
java
IInstanceProfile instanceProfile = InstanceProfile.fromInstanceProfileArn(this, "ImportedInstanceProfile", "arn:aws:iam::account-id:instance-profile/MyInstanceProfile");
csharp
var instanceProfile = InstanceProfile.FromInstanceProfileArn(this, "ImportedInstanceProfile", "arn:aws:iam::account-id:instance-profile/MyInstanceProfile");
go
instanceProfile := iam.InstanceProfile_FromInstanceProfileArn(this, jsii.String("ImportedInstanceProfile"), jsii.String("arn:aws:iam::account-id:instance-profile/MyInstanceProfile"))

To import an existing instance profile with an associated role:

ts
const role = new iam.Role(this, 'Role', {
  assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'),
});

const instanceProfile = iam.InstanceProfile.fromInstanceProfileAttributes(this, 'ImportedInstanceProfile', {
  instanceProfileArn: 'arn:aws:iam::account-id:instance-profile/MyInstanceProfile',
  role,
});
python
role = iam.Role(self, "Role",
    assumed_by=iam.ServicePrincipal("ec2.amazonaws.com")
)

instance_profile = iam.InstanceProfile.from_instance_profile_attributes(self, "ImportedInstanceProfile",
    instance_profile_arn="arn:aws:iam::account-id:instance-profile/MyInstanceProfile",
    role=role
)
java
Role role = Role.Builder.create(this, "Role")
        .assumedBy(new ServicePrincipal("ec2.amazonaws.com"))
        .build();

IInstanceProfile instanceProfile = InstanceProfile.fromInstanceProfileAttributes(this, "ImportedInstanceProfile", InstanceProfileAttributes.builder()
        .instanceProfileArn("arn:aws:iam::account-id:instance-profile/MyInstanceProfile")
        .role(role)
        .build());
csharp
var role = new Role(this, "Role", new RoleProps {
    AssumedBy = new ServicePrincipal("ec2.amazonaws.com")
});

var instanceProfile = InstanceProfile.FromInstanceProfileAttributes(this, "ImportedInstanceProfile", new InstanceProfileAttributes {
    InstanceProfileArn = "arn:aws:iam::account-id:instance-profile/MyInstanceProfile",
    Role = role
});
go
role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("ec2.amazonaws.com")),
})

instanceProfile := iam.InstanceProfile_FromInstanceProfileAttributes(this, jsii.String("ImportedInstanceProfile"), &InstanceProfileAttributes{
	InstanceProfileArn: jsii.String("arn:aws:iam::account-id:instance-profile/MyInstanceProfile"),
	Role: Role,
})

Features ​

  • Policy name uniqueness is enforced. If two policies by the same name are attached to the same principal, the attachment will fail.
  • Policy names are not required - the CDK logical ID will be used and ensured to be unique.
  • Policies are validated during synthesis to ensure that they have actions, and that policies attached to IAM principals specify relevant resources, while policies attached to resources specify both which IAM principals they apply to and which resources they govern.

Types ​

NameKindSummary
AccessKeyConstruct (L2)Define a new IAM Access Key.
GroupConstruct (L2)An IAM Group (collection of IAM users) lets you specify permissions for multiple users, which can make it easier to manage permissions for those users.
InstanceProfileConstruct (L2)IAM Instance Profile.
LazyRoleConstruct (L2)An IAM role that only gets attached to the construct tree once it gets used, not before.
ManagedPolicyConstruct (L2)Managed policy.
OidcProviderNativeConstruct (L2)IAM OIDC identity providers are entities in IAM that describe an external identity provider (IdP) service that supports the OpenID Connect (OIDC) standard, such as Google or Salesforce.
OpenIdConnectProviderConstruct (L2)IAM OIDC identity providers are entities in IAM that describe an external identity provider (IdP) service that supports the OpenID Connect (OIDC) standard, such as Google or Salesforce.
PolicyConstruct (L2)The AWS::IAM::Policy resource associates an inline IAM policy with IAM users, roles, or groups. For more information about IAM policies, see Overview of IAM Policies in the IAM User Guide guide.
RoleConstruct (L2)IAM Role.
SamlProviderConstruct (L2)A SAML provider.
UserConstruct (L2)Define a new IAM user.
CfnAccessKeyConstruct (L1)Creates a new AWS secret access key and corresponding AWS access key ID for the specified user.
CfnGroupConstruct (L1)Creates a new group.
CfnGroupPolicyConstruct (L1)Adds or updates an inline policy document that is embedded in the specified IAM group.
CfnInstanceProfileConstruct (L1)Creates a new instance profile. For information about instance profiles, see Using instance profiles .
CfnManagedPolicyConstruct (L1)Creates a new managed policy for your AWS account .
CfnOIDCProviderConstruct (L1)Creates or updates an IAM entity to describe an identity provider (IdP) that supports OpenID Connect (OIDC) .
CfnPolicyConstruct (L1)Adds or updates an inline policy document that is embedded in the specified IAM group, user or role.
CfnRoleConstruct (L1)Creates a new role for your AWS account .
CfnRolePolicyConstruct (L1)Adds or updates an inline policy document that is embedded in the specified IAM role.
CfnSAMLProviderConstruct (L1)Creates an IAM resource that describes an identity provider (IdP) that supports SAML 2.0.
CfnServerCertificateConstruct (L1)Uploads a server certificate entity for the AWS account .
CfnServiceLinkedRoleConstruct (L1)Creates an IAM role that is linked to a specific AWS service.
CfnUserConstruct (L1)Creates a new IAM user for your AWS account .
CfnUserPolicyConstruct (L1)Adds or updates an inline policy document that is embedded in the specified IAM user.
CfnUserToGroupAdditionConstruct (L1)Adds the specified user to the specified group.
CfnVirtualMFADeviceConstruct (L1)Creates a new virtual MFA device for the AWS account .
AccessKeyPropsStructProperties for defining an IAM access key.
AccessKeyStatusEnumValid statuses for an IAM Access Key.
AccountPrincipalClassSpecify AWS account ID as the principal entity in a policy to delegate authority to the account.
AccountRootPrincipalClassUse the AWS account into which a stack is deployed as the principal entity in a policy.
AddToPrincipalPolicyResultStructResult of calling addToPrincipalPolicy.
AddToResourcePolicyResultStructResult of calling addToResourcePolicy.
AnyPrincipalClassA principal representing all AWS identities in all accounts.
ArnPrincipalClassSpecify a principal by the Amazon Resource Name (ARN).
CanonicalUserPrincipalClassA policy principal for canonicalUserIds - useful for S3 bucket policies that use Origin Access identities.
CfnAccessKeyPropsStructProperties for defining a CfnAccessKey.
CfnGroup.PolicyPropertyStructContains information about an attached policy.
CfnGroupPolicyPropsStructProperties for defining a CfnGroupPolicy.
CfnGroupPropsStructProperties for defining a CfnGroup.
CfnInstanceProfilePropsStructProperties for defining a CfnInstanceProfile.
CfnManagedPolicyPropsStructProperties for defining a CfnManagedPolicy.
CfnOIDCProviderPropsStructProperties for defining a CfnOIDCProvider.
CfnPolicyPropsStructProperties for defining a CfnPolicy.
CfnRole.PolicyPropertyStructContains information about an attached policy.
CfnRolePolicyPropsStructProperties for defining a CfnRolePolicy.
CfnRolePropsStructProperties for defining a CfnRole.
CfnSAMLProvider.SAMLPrivateKeyPropertyStructContains the private keys for the SAML provider.
CfnSAMLProviderPropsStructProperties for defining a CfnSAMLProvider.
CfnServerCertificatePropsStructProperties for defining a CfnServerCertificate.
CfnServiceLinkedRolePropsStructProperties for defining a CfnServiceLinkedRole.
CfnUser.LoginProfilePropertyStructCreates a password for the specified user, giving the user the ability to access AWS services through the AWS Management Console .
CfnUser.PolicyPropertyStructContains information about an attached policy.
CfnUserPolicyPropsStructProperties for defining a CfnUserPolicy.
CfnUserPropsStructProperties for defining a CfnUser.
CfnUserToGroupAdditionPropsStructProperties for defining a CfnUserToGroupAddition.
CfnVirtualMFADevicePropsStructProperties for defining a CfnVirtualMFADevice.
CommonGrantOptionsStructBasic options for a grant operation.
ComparablePrincipalClassHelper class for working with IComparablePrincipals.
CompositeDependableClassComposite dependable.
CompositePrincipalClassRepresents a principal that has multiple types of principals.
CustomizeRolesOptionsStructOptions for customizing IAM role creation.
DefaultEncryptedResourceFactoriesClassDefault factories for encrypted resources.
DefaultPolicyFactoriesClassDefault factories for resources with policies.
EffectEnumThe Effect element of an IAM policy.
EncryptedResourcesClassUtility class for discovering and registering encrypted resource traits.
FederatedPrincipalClassPrincipal entity that represents a federated identity provider such as Amazon Cognito, that can be used to provide temporary security credentials to users who have been authenticated.
FromRoleArnOptionsStructOptions allowing customizing the behavior of Role.fromRoleArn.
FromRoleNameOptionsStructOptions allowing customizing the behavior of Role.fromRoleName.
GrantClassResult of a grant() operation.
GrantableResourcesClassUtility methods to check for specific types of grantable resources.
GrantOnKeyResultStructResult of a call to grantOnKey().
GrantOnPrincipalAndResourceOptionsStructOptions for a grant operation to both identity and resource.
GrantOnPrincipalOptionsStructOptions for a grant operation that only applies to principals.
GrantPolicyWithResourceOptionsStructOptions for a grant operation that directly adds a policy statement to a resource.
GrantWithResourceOptionsStructOptions for a grant operation.
GroupPropsStructProperties for defining an IAM group.
IAccessKeyInterfaceRepresents an IAM Access Key.
IAssumeRolePrincipalInterfaceA type of principal that has more control over its own representation in AssumeRolePolicyDocuments.
IComparablePrincipalInterfaceInterface for principals that can be compared.
IEncryptedResourceTraitA resource that contains data that can be encrypted, using a KMS key.s.
IEncryptedResourceFactoryTraitFactory interface for creating IEncryptedResource instances from constructs.
IGrantableInterfaceAny object that has an associated principal that a permission can be granted to.
IGroupInterfaceRepresents an IAM Group.
IIdentityInterfaceA construct that represents an IAM principal, such as a user, group or role.
IInstanceProfileInterfaceRepresents an IAM Instance Profile.
IManagedPolicyInterfaceA managed policy.
InstanceProfileAttributesStructAttributes of an Instance Profile.
InstanceProfilePropsStructProperties of an Instance Profile.
IOidcProviderInterfaceRepresents an IAM OpenID Connect provider.
IOpenIdConnectProviderInterfaceRepresents an IAM OpenID Connect provider.
IPolicyInterfaceRepresents an IAM Policy.
IPrincipalInterfaceRepresents a logical IAM principal.
IResourcePolicyFactoryTraitFactory interface for creating IResourceWithPolicyV2 instances from constructs.
IResourceWithPolicyInterfaceA resource with a resource policy that can be added to.
IResourceWithPolicyV2TraitA resource with a resource policy that can be added to.
IRoleInterfaceA Role object.
ISamlProviderInterfaceA SAML provider.
IUserInterfaceRepresents an IAM user.
LazyRolePropsStructProperties for defining a LazyRole.
ManagedPolicyPropsStructProperties for defining an IAM managed policy.
OidcProviderNativePropsStructInitialization properties for OIDCProviderNative.
OpenIdConnectPrincipalClassA principal that represents a federated identity provider as from a OpenID Connect provider.
OpenIdConnectProviderPropsStructInitialization properties for OpenIdConnectProvider.
OrganizationPrincipalClassA principal that represents an AWS Organization.
PermissionsBoundaryClassModify the Permissions Boundaries of Users and Roles in a construct tree.
PolicyDocumentClassA PolicyDocument is a collection of statements.
PolicyDocumentPropsStructProperties for a new PolicyDocument.
PolicyPropsStructProperties for defining an IAM inline policy document.
PolicyStatementClassRepresents a statement in an IAM policy document.
PolicyStatementPropsStructInterface for creating a policy statement.
PrincipalBaseClassBase class for policy principals.
PrincipalPolicyFragmentClassA collection of the fields in a PolicyStatement that can be used to identify a principal.
PrincipalWithConditionsClassAn IAM principal with additional conditions specifying when the policy is in effect.
ResourcePolicyValidationOptionsStructOptions for resource-based policy validation.
ResourceWithPoliciesClassUtility class for discovering and managing resource policy traits.
RoleGrantsFacadeCollection of grant methods for a IRoleRef.
RoleLookupOptionsStructProperties for looking up an existing Role.
RolePropsStructProperties for defining an IAM Role.
SamlConsolePrincipalClassPrincipal entity that represents a SAML federated identity provider for programmatic and AWS Management Console access.
SamlMetadataDocumentClassA SAML metadata document.
SamlPrincipalClassPrincipal entity that represents a SAML federated identity provider.
SamlProviderPropsStructProperties for a SAML provider.
ServicePrincipalClassAn IAM principal that represents an AWS service (i.e. sqs.amazonaws.com).
ServicePrincipalOptsStructOptions for a service principal.
SessionTagsPrincipalClassEnables session tags on role assumptions from a principal.
StarPrincipalClassA principal that uses a literal '*' in the IAM JSON language.
UnknownPrincipalClassA principal for use in resources that need to have a role but it's unknown.
UnknownPrincipalPropsStructProperties for an UnknownPrincipal.
UserAttributesStructRepresents a user defined outside of this stack.
UserPropsStructProperties for defining an IAM user.
WebIdentityPrincipalClassA principal that represents a federated identity provider as Web Identity such as Cognito, Amazon, Facebook, Google, etc.
WithoutPolicyUpdatesOptionsStructOptions for the withoutPolicyUpdates() modifier of a Role.