How to Use AWS CLI to Create an Execution Role that Allows a Lambda Function to Get Objects From an Amazon S3 Bucket and Write to Amazon CloudWatch Logs

Hemanta Sundaray

Published January 19, 2024


Follow the steps below to create an execution role that grants a Lambda function the necessary permissions to get objects from an S3 bucket and write to Amazon CloudWatch logs.

Step-1: Create an Execution Role

Run the following command to create an execution role with the trust relationship policy document provided directly in the command:

aws iam create-role \
--role-name <ROLE_NAME> \
--assume-role-policy-document '{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}'

Replace <ROLE_NAME> with a name of your choice for the execution role.

Note

A trust relationship policy document is a JSON-formatted document that defines which entities (users, services, or other roles) are allowed to assume a given IAM role.

When you create an execution role for AWS Lambda, this role is not automatically associated with the Lambda service. The trust relationship policy document explicitly grants the Lambda service the permission to assume this role. Without this policy, AWS Lambda wouldn't be able to use the role, and consequently, your Lambda function wouldn't be able to interact with other AWS services.

Step 2: Attach Policies to the Execution Role

With the role created, the next step is to attach policies that define what actions the Lambda function can perform. Based on our requirements, we’ll attach the following two predefined AWS policies:

AWSLambdaBasicExecutionRole

This policy allows the function to write logs to CloudWatch. To attach this policy, run the following command:

aws iam attach-role-policy --role-name <ROLE_NAME> --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

Replace <ROLE_NAME> with the name of your execution role.

AmazonS3ReadOnlyAcces

This policy grants the function read-only access to S3 buckets. To attach this policy, run the following command:

aws iam attach-role-policy --role-name <ROLE_NAME> --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

Replace <ROLE_NAME> with the name of your execution role.

AmazonS3FullAcces

This policy grants the function full access (read, write, delete, etc.) to S3 buckets. To attach this policy, run the following command:

aws iam attach-role-policy --role-name <ROLE_NAME> --policy-arn arn:aws:iam::aws:policy/AmazonS3FullAccess

Replace <ROLE_NAME> with the name of your execution role.

Note

In AWS, a "predefined policy" refers to a set of permissions that have been created and managed by AWS. These policies are designed to provide a convenient and secure way to grant specific permissions to AWS resources, like users, groups, or roles.