Sub topic 4
Giving a Function Permissions with an Execution Role
This chapter assumes you know what an IAM role and a policy document are, can read JSON policies, and have written a basic Lambda handler. By the end you will be able to attach the right permissions to a function, tell apart the two directions of Lambda access control, and diagnose the common AccessDenied errors.
Two directions of access
Lambda permissions run in two directions, and mixing them up causes most of the confusion.
- Outbound: what your function is allowed to do to other AWS services, such as writing to DynamoDB or reading from S3. This is controlled by the execution role.
- Inbound: who or what is allowed to invoke or manage your function, such as API Gateway, S3, or another account. This is controlled by the function's resource-based policy.
What an execution role is
An execution role is an IAM role that Lambda assumes each time it runs your function. Lambda calls AWS STS on your behalf and hands your code temporary credentials. These credentials are exposed to the function as environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN. The AWS SDK reads them automatically, so you never put keys in your code.
Every function has exactly one execution role. Several functions can share a role, but a separate role per function is easier to keep least-privilege.
A role has two parts that matter here:
- Trust policy. It states who may assume the role. For Lambda it must allow the service principal
lambda.amazonaws.comto callsts:AssumeRole. - Permissions policies. They state what the role may do once assumed.
A minimal trust policy looks like this:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "lambda.amazonaws.com" },
"Action": "sts:AssumeRole"
}
]
}If the trust policy names the wrong principal, Lambda cannot assume the role and the function fails to create or invoke.
Logging permissions come first
Almost every function needs to write logs. Lambda sends output to CloudWatch Logs using the execution role, so the role needs these actions:
logs:CreateLogGrouplogs:CreateLogStreamlogs:PutLogEvents
AWS provides a managed policy, AWSLambdaBasicExecutionRole, that grants exactly these. If a function runs but you see no logs, a missing logging permission is the first thing to check. The role lacks the permissions, so Lambda cannot write the log group and the function's output vanishes.
Adding least-privilege permissions
Beyond logging, grant only what the code calls. The handler from this tutorial writes one item to one DynamoDB table with put_item. It needs dynamodb:PutItem on that table and nothing else.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "dynamodb:PutItem",
"Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/Orders"
}
]
}Compare this with a broad policy such as dynamodb:* on *. The broad version works, but if the function is compromised or has a bug, it can delete any table in the account. A narrow policy limits the damage.
Guidelines for writing these policies:
- Name specific actions rather than wildcards.
- Name specific resource ARNs rather than
*. Some actions do not support resource-level restrictions, and for those*is required. - Prefer customer-managed or inline policies for application permissions. AWS managed policies are convenient but often broader than you need.
- Use condition keys when they help, for example restricting a role to a given tag or prefix.
Permissions for poll-based event sources
For poll-based sources, Lambda reads from the source on your behalf, and it uses your execution role to do so. An SQS trigger therefore needs these actions on the queue:
sqs:ReceiveMessagesqs:DeleteMessagesqs:GetQueueAttributes
AWS provides AWSLambdaSQSQueueExecutionRole for this. Similar managed policies exist for Kinesis and DynamoDB streams. If the role lacks these, the event source mapping cannot read messages. The mapping may show a state such as "Problem", and messages stay in the queue.
Defining the role with AWS SAM
In SAM you usually do not write the role by hand. The Policies property creates the role and attaches the policies. This is the pattern from the SAM template in this tutorial:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
OrdersFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
Runtime: python3.12
CodeUri: src/
MemorySize: 256
Timeout: 10
Environment:
Variables:
TABLE_NAME: !Ref OrdersTable
Policies:
- DynamoDBCrudPolicy:
TableName: !Ref OrdersTable
Events:
CreateOrder:
Type: HttpApi
Properties:
Path: /orders
Method: post
OrdersTable:
Type: AWS::Serverless::SimpleTableDynamoDBCrudPolicy is a SAM policy template. SAM expands it into a policy scoped to the named table, and it adds the basic logging permissions automatically. Note that this template grants create, read, update and delete on the table. The handler only needs PutItem, so you can tighten it by replacing the template with an inline statement:
Policies:
- Statement:
- Effect: Allow
Action: dynamodb:PutItem
Resource: !GetAtt OrdersTable.ArnIf you already have a role, use the Role property with its ARN instead of Policies. Setting both is not how SAM expects you to work: with Role set, SAM does not create a role, so it ignores Policies.
Resource-based policies: the inbound side
A resource-based policy is attached to the function itself. It says which principals may call lambda:InvokeFunction on it. You rarely write it by hand when you use SAM, because declaring an event under Events adds the needed statement for you. When you wire things manually, you add it with the CLI:
aws lambda add-permission \
--function-name orders-function \
--statement-id AllowS3Invoke \
--action lambda:InvokeFunction \
--principal s3.amazonaws.com \
--source-arn arn:aws:s3:::my-upload-bucket \
--source-account 123456789012The --source-arn and --source-account options matter. Without them, any S3 bucket in any account could invoke your function, because the principal s3.amazonaws.com is shared by all customers. Restricting by source avoids the "confused deputy" problem, where a service is tricked into acting for the wrong party.
Which side applies depends on the trigger:
| Trigger type | Who calls the function | Permission needed |
|---|---|---|
| API Gateway, S3, SNS (push) | The service invokes the function | Resource-based policy on the function |
| SQS, Kinesis, DynamoDB streams (poll) | Lambda polls the source | Execution role needs read access to the source |
| Your own code calling `Invoke` | The caller's identity | Caller's IAM policy allows `lambda:InvokeFunction` |
For the last row, the caller's identity-based policy must allow the invoke. The function's resource policy must also allow it if the caller is in a different account.
Cross-account and `iam:PassRole`
When you create or update a function, you pass a role to Lambda. The identity doing this needs iam:PassRole on that role. This stops a user with limited rights from handing a powerful role to a function and then using the function to act with that power. Scope iam:PassRole to the specific role ARNs, and add a condition iam:PassedToService set to lambda.amazonaws.com.
Diagnosing permission errors
Read the error message first. It usually names the action and the resource.
| Symptom | Likely cause | Fix |
|---|---|---|
| `AccessDeniedException` inside the function when calling DynamoDB or S3 | The execution role lacks the action, or the resource ARN does not match | Add the action and check the ARN, including the region and the `/*` suffix for S3 objects |
| No logs in CloudWatch | Role lacks `logs:*` actions | Attach `AWSLambdaBasicExecutionRole` |
| Trigger fires but the function never runs | Resource-based policy missing, or the source ARN does not match | Add or correct the permission with `add-permission` |
| SQS messages are not consumed | Role lacks `sqs:ReceiveMessage` and related actions | Attach queue permissions |
| `The role defined for the function cannot be assumed by Lambda` | Trust policy does not allow `lambda.amazonaws.com` | Fix the trust policy |
| `User is not authorized to perform iam:PassRole` | Deployer lacks `iam:PassRole` | Grant it, scoped to the role |
Two edge cases are worth knowing:
- S3 ARNs have two forms.
arn:aws:s3:::bucketrefers to the bucket, used fors3:ListBucket.arn:aws:s3:::bucket/*refers to objects, used fors3:GetObject. A policy with only one form fails for the other action. - Policy changes take a moment. IAM is eventually consistent, so a freshly created role or policy can fail for a few seconds. A retry usually succeeds. Running functions pick up new permissions on their next credential refresh, so a warm environment may briefly use old credentials.
You can see which identity your code runs as with a short check:
import boto3
sts = boto3.client("sts")
print(sts.get_caller_identity()["Arn"])The ARN printed will look like arn:aws:sts::123456789012:assumed-role/OrdersFunctionRole-ABC123/orders-function. It confirms which role is in effect.
Exercises
Exercise
A function triggered by an SQS queue deploys without errors, but messages stay in the queue and the function never runs. The function's code is correct. Which permission do you check, and on which identity?
Show answer
Check the execution role. For poll-based sources, Lambda reads from the queue using the execution role, so the role needs sqs:ReceiveMessage, sqs:DeleteMessage and sqs:GetQueueAttributes on the queue's ARN. A resource-based policy on the function is not the cause, because Lambda polls the queue itself and the queue does not call the function.
Exercise
You configure S3 to invoke your function when objects are uploaded, and you set the function's execution role to allow s3:GetObject. Uploads still do not trigger the function. What is missing, and why is the execution role not the fix?
Show answer
The function needs a resource-based policy that allows s3.amazonaws.com to call lambda:InvokeFunction, ideally restricted with the bucket's source ARN and the account ID. The execution role controls what the function can do after it starts, such as reading the object. It does not control whether S3 is allowed to start the function.