Sub topic 7
Granting permissions with grant methods
This chapter covers how CDK constructs give one resource access to another. It assumes you know what an IAM role and policy are, and that you have read the chapters on defining resources and on L2 constructs.
The problem grant methods solve
In plain CloudFormation, letting a Lambda function read an S3 bucket takes several pieces. You write an AWS::IAM::Role, an AWS::IAM::Policy with the right actions, and the exact resource ARNs. The ARNs must include both the bucket (arn:aws:s3:::name) and its objects (arn:aws:s3:::name/*). Mistakes here usually mean either an AccessDenied error at runtime or a policy that is far too broad.
L2 constructs answer this with grant methods. A grant method is a method on a resource that takes a principal (something that can hold permissions, such as a role or a function) and adds the right statements to that principal's policy.
bucket.grantRead(fn);This one line is in the stack from the earlier chapter. It does the following:
- Finds the execution role that the CDK created for
fn. - Adds a statement to that role's policy.
- Lists the S3 read actions the CDK team chose for the "read" operation, such as
s3:GetObject*,s3:GetBucket*ands3:List*. - Scopes the statement to the bucket ARN and the
bucket/*ARN.
You never write an ARN or an action name.
Where grants appear in the template
Run cdk synth and look at the output. The function's role gets a generated policy resource:
ProcessorServiceRoleDefaultPolicy:
Type: AWS::IAM::Policy
Properties:
PolicyDocument:
Statement:
- Action:
- s3:GetObject*
- s3:GetBucket*
- s3:List*
Effect: Allow
Resource:
- Fn::GetAtt: [UploadsBucket..., Arn]
- Fn::Join: ["", [Fn::GetAtt: [UploadsBucket..., Arn], "/*"]]
Roles:
- Ref: ProcessorServiceRole...The exact action list can change between CDK versions. The Fn::GetAtt calls are tokens, which the chapter on tokens covers. They let the CDK refer to the bucket's ARN before the bucket exists.
Common grant methods
Most L2 constructs that hold data or accept calls have grant methods. Names follow a pattern in both languages: grantX in TypeScript and grant_x in Python.
| Resource | Methods | Typical use |
|---|---|---|
| `s3.Bucket` | `grantRead`, `grantWrite`, `grantReadWrite`, `grantDelete`, `grantPut` | Function reads or writes objects |
| `dynamodb.Table` | `grantReadData`, `grantWriteData`, `grantReadWriteData`, `grantFullAccess` | Function queries or updates items |
| `sqs.Queue` | `grantSendMessages`, `grantConsumeMessages` | Producer and consumer split |
| `sns.Topic` | `grantPublish` | Publishing notifications |
| `lambda.Function` | `grantInvoke` | Another service calls the function |
| `secretsmanager.Secret` | `grantRead`, `grantWrite` | Reading a database password |
Use the narrowest method that fits. A function that only uploads files needs grantWrite (or grantPut), not grantReadWrite. This is least privilege, and the grant methods make it as easy to do as the broad option.
The same call in Python
The model is identical in Python. Only the naming differs.
bucket.grant_read(fn)Granting to roles and other principals
The target of a grant can be anything that implements the IGrantable interface. Functions, roles, users, groups and CodeBuild projects all qualify. You can grant to an explicit role:
import * as iam from 'aws-cdk-lib/aws-iam';
const auditRole = new iam.Role(this, 'AuditRole', {
assumedBy: new iam.AccountRootPrincipal(),
});
bucket.grantRead(auditRole);Grants also work in the other direction for service principals. For example, fn.grantInvoke(new iam.ServicePrincipal('events.amazonaws.com')) adds a resource-based policy to the function itself rather than an identity policy on a role.
Identity policies and resource policies
A grant method decides which kind of policy to write. Two kinds exist:
- An identity-based policy is attached to the principal (the role). Most grants to roles use this.
- A resource-based policy is attached to the resource (a bucket policy or a Lambda permission). Grants use this when the principal is in another account or is a service principal.
Within one account, the CDK normally writes only the identity policy. For cross-account grants, the CDK writes both sides, because AWS requires both to allow the access. You do not choose this. The grant method inspects the principal's account and does the right thing.
Encryption keys follow along
If the bucket is encrypted with a customer-managed KMS key, reading it also needs kms:Decrypt. The grant method handles this too. When you pass encryptionKey to the bucket, grantRead adds the key permissions as well. Doing this by hand is a frequent source of confusing AccessDenied errors.
Working with the Grant object
Every grant method returns a Grant object. Normally you ignore it. It has useful methods when you need them:
grant.assertSuccess()throws if the grant could not be added. Some grants do nothing on an imported resource (for example, a bucket imported by name from another account), and this call makes the failure visible.grant.applyBefore(...)makes another construct wait until the grant exists. This fixes ordering problems where a resource starts using a permission before the policy has been created.
When no grant method exists
Not every construct or action has a grant method. Use addToRolePolicy on a function, or addToPrincipalPolicy on a role, with an explicit statement:
import * as iam from 'aws-cdk-lib/aws-iam';
fn.addToRolePolicy(new iam.PolicyStatement({
actions: ['ses:SendEmail'],
resources: ['arn:aws:ses:us-east-1:123456789012:identity/example.com'],
}));Keep resources as narrow as you can. Avoid '*' unless the action truly does not support resource-level permissions.
Common errors
- Granting on an imported resource.
Bucket.fromBucketNameproduces a bucket where the CDK cannot see encryption settings or the owning account, so the grant may be incomplete. Check the synthesized template. - Granting too much.
grantReadWriteis easy to reach for. Reviewcdk diff, which prints an IAM statement table for every change in permissions, before you deploy. - Circular dependencies. Granting between resources in two different stacks can create a dependency cycle, since each stack now refers to the other. Keep grants within one stack, or pass the principal and resource in one direction only.
- Expecting changes to the running function without a deploy. A grant exists only after
cdk deployupdates the policy.
Exercise
A function must write new files to a bucket but must never read or delete existing ones. Which grant method should you use, and what do you check before deploying?
Show answer
Use bucket.grantPut(fn) (or grantWrite if overwriting and multipart uploads need to be covered, noting grantWrite also includes delete actions in some versions, so check the output). Then run cdk diff and read the IAM Statement Changes table to confirm only the put-style actions appear on the bucket's object ARN.
Exercise
What does the CDK add to the template when you call bucket.grantRead(fn), and why do you not write an ARN?
Show answer
It adds an AWS::IAM::Policy attached to the function's execution role, with read actions on the bucket ARN and the bucket/* ARN. The ARNs are tokens that the CDK fills in from the bucket construct, so you never type them.