Package: aws-cdk.aws-iam
AWS Identity and Access Management Construct Library---AWS CDK v1 has reached End-of-Support on 2023-06-01.
This package is no longer being updated, and users should migrate to AWS CDK v2.For more information on how to migrate, see theMigrating to AWS CDK v2guide.Define a role and add permissions to it. This will automatically create and
attach an IAM policy to the role:role=Role(self,"MyRole",assumed_by=ServicePrincipal("sns.amazonaws.com"))role.add_to_policy(PolicyStatement(resources=["*"],actions=["lambda:InvokeFunction"]))Define a policy and attach it to groups, users and roles. Note that it is possible to attach
the policy either by callingxxx.attachInlinePolicy(policy)orpolicy.attachToXxx(xxx).user=User(self,"MyUser",password=cdk.SecretValue.unsafe_plain_text("1234"))group=Group(self,"MyGroup")policy=Policy(self,"MyPolicy")policy.attach_to_user(user)group.attach_inline_policy(policy)Managed policies can be attached usingxxx.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName)):group=Group(self,"MyGroup")group.add_managed_policy(ManagedPolicy.from_aws_managed_policy_name("AdministratorAccess"))Granting permissions to resourcesMany of the AWS CDK resources havegrant*methods 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.# fn: lambda.Function# table: dynamodb.Tabletable.grant_write_data(fn)The more genericgrantmethod allows you to give specific permissions to a resource:# fn: lambda.Function# table: dynamodb.Tabletable.grant(fn,"dynamodb:PutItem")Thegrant*methods accept anIGrantableobject. This interface is implemented by IAM principlal resources (groups, users and roles) and resources that assume a role such as a Lambda function, EC2 instance or a Codebuild project.You can find whichgrant*methods exist for a resource in theAWS CDK API Reference.RolesMany AWS resources requireRolesto 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 permissionsStatementsis
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 anAWS CodePipelineto trigger
anAWS Lambda Function, the Pipeline's Role will automatically getlambda:InvokeFunctionpermissions on that particular Lambda Function),
or if you explicitly grant permissions usinggrantfunctions (see the
previous section).Opting out of automatic permissions managementYou 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 bymyRole.withoutPolicyUpdates()instead ofmyRoleitself.For example, to have an AWS CodePipelinenotautomatically add the required
permissions to trigger the expected targets, do the following:role=iam.Role(self,"Role",assumed_by=iam.ServicePrincipal("codepipeline.amazonaws.com"),# custom description if desireddescription="This is a custom role...")codepipeline.Pipeline(self,"Pipeline",# Give the Pipeline an immutable view of the Rolerole=role.without_policy_updates())# You now have to manage the Role policies yourselfrole.add_to_policy(iam.PolicyStatement(actions=[],resources=[]))Using existing rolesIf there are Roles in your account that have already been created which you
would like to use in your CDK application, you can useRole.fromRoleArnto
import them, as follows: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)Configuring an ExternalIdIf you need to create Roles that will be assumed by third parties, it is generally a good idea torequire anExternalIdto assume them.  Configuring
anExternalIdworks like this:role=iam.Role(self,"MyRole",assumed_by=iam.AccountPrincipal("123456789012"),external_ids=["SUPPLY-ME"])Principals vs IdentitiesWhen we sayPrincipal, 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". AnIdentityis an IAM representing a single IAM entity that can have
a policy attached, one ofRole,User, orGroup.IAM PrincipalsWhen 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
underPrincipal.IAM principals are modeled as classes that derive from theiam.PolicyPrincipalabstract 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 abstractstatement.addPrincipal, one of the concreteaddXxxPrincipalmethods:addAwsPrincipal,addArnPrincipalornew ArnPrincipal(arn)for{ "AWS": arn }addAwsAccountPrincipalornew AccountPrincipal(accountId)for{ "AWS": account-arn }addServicePrincipalornew ServicePrincipal(service)for{ "Service": service }addAccountRootPrincipalornew AccountRootPrincipal()for{ "AWS": { "Ref: "AWS::AccountId" } }addCanonicalUserPrincipalornew CanonicalUserPrincipal(id)for{ "CanonicalUser": id }addFederatedPrincipalornew FederatedPrincipal(federated, conditions, assumeAction)for{ "Federated": arn }and a set of optional conditions and the assume role action to use.addAnyPrincipalornew AnyPrincipalfor{ "AWS": "*" }If multiple principals are added to the policy statement, they will be merged together: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")Will result in:{"Principal":{"Service":["cloudwatch.amazonaws.com","ec2.amazonaws.com"],"AWS":"arn:aws:boom:boom"}}TheCompositePrincipalclass can also be used to define complex principals, for example:role=iam.Role(self,"MyRole",assumed_by=iam.CompositePrincipal(iam.ServicePrincipal("ec2.amazonaws.com"),iam.AccountPrincipal("1818188181818187272")))ThePrincipalWithConditionsclass can be used to add conditions to a
principal, especially those that don't take aconditionsparameter in their
constructor. Theprincipal.withConditions()method can be used to create aPrincipalWithConditionsfrom an existing principal, for example:principal=iam.AccountPrincipal("123456789000").with_conditions({"StringEquals":{"foo":"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, useCfnJsonto
render this condition. Seethis testfor
an example.TheWebIdentityPrincipalclass can be used as a principal for web identities like
Cognito, Amazon, Google or Facebook, for example: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"}})If your identity provider is configured to assume a Role withsession
tags, you
need to call.withSessionTags()to add the required permissions to the Role's
policy document: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())Parsing JSON Policy DocumentsThePolicyDocument.fromJsonandPolicyStatement.fromJsonstatic methods can be used to parse JSON objects. For example: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)Permissions BoundariesPermissions
Boundariescan be used as a mechanism to prevent privilege esclation by creating newRoles. Permissions Boundaries are a Managed Policy, attached to Roles or
Users, that represent themaximumset 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 createdRoles will be enforced by
IAM policies.It is possible to attach Permissions Boundaries to all Roles created in a construct
tree all at once:# 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 boundaryboundary2=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 stackiam.PermissionsBoundary.of(self).apply(boundary)iam.PermissionsBoundary.of(custom_resource).clear()OpenID Connect ProvidersOIDC identity providers are entities in IAM that describe an external identity
provider (IdP) service that supports theOpenID 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 tohttps://openid/connect.provider=iam.OpenIdConnectProvider(self,"MyProvider",url="https://openid/connect",client_ids=["myclient1","myclient2"])You can specify an optional list ofthumbprints. If not specified, the
thumbprint of the root certificate authority (CA) will automatically be obtained
from the host as describedhere.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 anAmazon
Cognito identity
poolyou can reference the provider's ARN as follows:importaws_cdk.aws_cognitoascognito# my_provider: iam.OpenIdConnectProvidercognito.CfnIdentityPool(self,"IdentityPool",open_id_connect_provider_arns=[my_provider.open_id_connect_provider_arn],# And the other properties for your identity poolallow_unauthenticated_identities=False)TheOpenIdConnectPrincipalclass can be used as a principal used with aOpenIdConnectProvider, for example:provider=iam.OpenIdConnectProvider(self,"MyProvider",url="https://openid/connect",client_ids=["myclient1","myclient2"])principal=iam.OpenIdConnectPrincipal(provider)SAML providerAn 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.iam.SamlProvider(self,"Provider",metadata_document=iam.SamlMetadataDocument.from_file("/path/to/saml-metadata-document.xml"))TheSamlPrincipalclass can be used as a principal with aSamlProvider: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"}})When creating a role for programmatic and AWS Management Console access, use theSamlConsolePrincipalclass: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))UsersIAM manages users for your AWS account. To create a new user:user=iam.User(self,"MyUser")To import an existing user by namewith path:user=iam.User.from_user_name(self,"MyImportedUserByName","johnsmith")To import an existing user by ARN:user=iam.User.from_user_arn(self,"MyImportedUserByArn","arn:aws:iam::123456789012:user/johnsmith")To import an existing user by attributes:user=iam.User.from_user_attributes(self,"MyImportedUserByAttributes",user_arn="arn:aws:iam::123456789012:user/johnsmith")Access KeysThe 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:user=iam.User(self,"MyUser")access_key=iam.AccessKey(self,"MyAccessKey",user=user)You can force CloudFormation to rotate the access key by providing a monotonically increasingserialproperty. Simply provide a higher serial value than any number used previously:user=iam.User(self,"MyUser")access_key=iam.AccessKey(self,"MyAccessKey",user=user,serial=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).GroupsAn IAM user group is a collection of IAM users. User groups let you specify permissions for multiple users.group=iam.Group(self,"MyGroup")To import an existing group by ARN:group=iam.Group.from_group_arn(self,"MyImportedGroupByArn","arn:aws:iam::account-id:group/group-name")To import an existing group by namewith path:group=iam.Group.from_group_name(self,"MyImportedGroupByName","group-name")To add a user to a group (both for a new and imported user/group):user=iam.User(self,"MyUser")# or User.fromUserName(stack, 'User', 'johnsmith');group=iam.Group(self,"MyGroup")# or Group.fromGroupArn(stack, 'Group', 'arn:aws:iam::account-id:group/group-name');user.add_to_group(group)# orgroup.add_user(user)FeaturesPolicy 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 which IAM principals they apply to.