S3 Policy to Allow Lambda

FiguringThisOut picture FiguringThisOut · Jul 24, 2017 · Viewed 25k times · Source

I have the following policy on an S3 bucket created with the AWS policy generator to allow a lambda, running with a specific role, access to the files in the bucket. However, when I execute the Lambda, I get 403 permission denied:

"errorMessage": "Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID: <requestId>)",
  "errorType": "com.amazonaws.services.s3.model.AmazonS3Exception",

The Policy on the S3 bucket:

{
"Version": "2012-10-17",
"Id": "Policy<number>",
"Statement": [
    {
        "Sid": "Stmt<number>",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::<account>:role/<roleName>"
        },
        "Action": "s3:*",
        "Resource": "arn:aws:s3:::<bucketName>/*"
    }
]
}

What is wrong with the policy? The Lamba is running with the role configured in the policy.

Answer

John Rotenstein picture John Rotenstein · Jul 25, 2017

A role assigned to an AWS Lambda function should be created an an AWS Lambda role (selected when creating a Role in the IAM console).

Roles do not have a Principal since the permissions are assigned to whichever service (in this case, Lambda function) is using the role.

Also, you should assign permissions on the bucket itself (eg to list contents) and on the contents of the bucket (eg to GetObject).

It would be something like this:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowS3Access",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::123XXX:role/service-role/LAMBDA_ROLE_NAME"
            },
            "Action": [
                "s3:*"
            ],
            "Resource": [
                "arn:aws:s3:::my-bucket",
                "arn:aws:s3:::my-bucket/*"
            ]
        }
    ]
}