Hands-On: Create a Role for Lambda

Use the AWS CLI to create the role our NoteSnap Lambda function will use.

1 min read

Every role has two policies:

  • A trust policy: who is allowed to assume the role (here, the Lambda service).
  • Permission policies: what the role can do once assumed.

First, check who you're signed in as. It's the "hello world" of AWS:

Terminal
aws sts get-caller-identity

Save this trust policy as trust.json:

JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Service": "lambda.amazonaws.com" },
    "Action": "sts:AssumeRole"
  }]
}

Then create the role and attach permissions:

Try it

Terminal
# 1. Create the role, saying only Lambda may assume it
aws iam create-role \
  --role-name notesnap-lambda-role \
  --assume-role-policy-document file://trust.json

# 2. Let it write logs to CloudWatch (an AWS-managed policy)
aws iam attach-role-policy \
  --role-name notesnap-lambda-role \
  --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

# 3. Add our own least-privilege S3 read policy from the previous lesson
aws iam put-role-policy \
  --role-name notesnap-lambda-role \
  --policy-name read-notes \
  --policy-document file://notesnap-read-policy.json

Copy the Arn from the output. You'll pass it to Lambda when you create the function in the Lambda tutorial.

Note

Newly created roles can take a few seconds to become usable everywhere. If Lambda complains the role "cannot be assumed" right after you create it, wait a moment and try again.

Key takeaways

  • A role needs a trust policy (who can assume it) plus permission policies (what it can do).
  • `aws sts get-caller-identity` tells you which identity your CLI is using.
  • AWS-managed policies such as AWSLambdaBasicExecutionRole cover common needs like writing logs.

Check your understanding

Pick an answer to see the explanation.

  1. 1. Which part of a role says that Lambda is allowed to use it?