Skip to main content

CDK routines for easily assigning correct and minimal IAM permissions

Project description

AWS Identity and Access Management Construct Library

---

Stability: Stable


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

# Example automatically generated. See https://github.com/aws/jsii/issues/826
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 calling xxx.attachInlinePolicy(policy) or policy.attachToXxx(xxx).

# Example automatically generated. See https://github.com/aws/jsii/issues/826
user = User(self, "MyUser", password=cdk.SecretValue.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 using xxx.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName)):

# Example automatically generated. See https://github.com/aws/jsii/issues/826
group = Group(self, "MyGroup")
group.add_managed_policy(ManagedPolicy.from_aws_managed_policy_name("policy/AdministratorAccess"))

Granting permissions to resources

Many of the AWS CDK resources have grant* 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.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
fn = lambda.Function(...)
table = dynamodb.Table(...)

table.grant_write_data(fn)

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

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
fn = lambda.Function(...)
table = dynamodb.Table(...)

table.grant(fn, "dynamodb:PutItem")

The grant* methods accept an IGrantable object. 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 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 grant functions (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:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
role = iam.Role(self, "Role",
    assumed_by=iam.ServicePrincipal("codepipeline.amazonaws.com")
)

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(
    action=[],
    resource=[]
))

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:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
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 ExternalId

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

# Example automatically generated. See https://github.com/aws/jsii/issues/826
role = iam.Role(self, "MyRole",
    assumed_by=iam.AccountPrincipal("123456789012"),
    external_ids=["SUPPLY-ME"]
)

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:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
statement = 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"
  }
}

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

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
role = iam.Role(self, "MyRole",
    assumed_by=iam.CompositePrincipal(
        iam.ServicePrincipal("ec2.amazonaws.com"),
        iam.AccountPrincipal("1818188181818187272"))
)

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.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aws-cdk.aws-iam-1.21.0.tar.gz (246.8 kB view details)

Uploaded Source

Built Distribution

aws_cdk.aws_iam-1.21.0-py3-none-any.whl (245.0 kB view details)

Uploaded Python 3

File details

Details for the file aws-cdk.aws-iam-1.21.0.tar.gz.

File metadata

  • Download URL: aws-cdk.aws-iam-1.21.0.tar.gz
  • Upload date:
  • Size: 246.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/39.0.1 requests-toolbelt/0.9.1 tqdm/4.41.1 CPython/3.6.5

File hashes

Hashes for aws-cdk.aws-iam-1.21.0.tar.gz
Algorithm Hash digest
SHA256 1e87c30efb7913335bd43d317c93952f6c6d2ce8566b15519f6ae80653be02d1
MD5 cb2555ba3f4f8190c0d09d0b624e2e03
BLAKE2b-256 db0a0126b45a1818222241da4ba01edb57b46daa7483ed8da21f30c9c5479f31

See more details on using hashes here.

File details

Details for the file aws_cdk.aws_iam-1.21.0-py3-none-any.whl.

File metadata

  • Download URL: aws_cdk.aws_iam-1.21.0-py3-none-any.whl
  • Upload date:
  • Size: 245.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/39.0.1 requests-toolbelt/0.9.1 tqdm/4.41.1 CPython/3.6.5

File hashes

Hashes for aws_cdk.aws_iam-1.21.0-py3-none-any.whl
Algorithm Hash digest
SHA256 52a5ee59e703ab4954549571de54ff2def7225db6bc45ef455c01c6b97033581
MD5 072b0728d0929909f828b4c1afc652cd
BLAKE2b-256 ac321173c4a9737934f4e8164e14546c9e4c10c34e2e049bc63f3b9dac9704ed

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page