The Role that allows API Gateway to upload objects in S3

Piero Bozzolo
Claranet-CH
Published in
3 min readJul 13, 2022

This article is a part of a series dedicated to API Gateway and its secrets.

If you want to create an API Gateway that allows customers to upload files directly to S3, You should make an IAM role. This Role must be assumable from API Gateway and has permissions to write objects on S3.

The first step is to open the IAM service in your AWS console. Then click on “Roles” (1) and “Create role”.(2)

Select “AWS service” (1) in “trusted entity type”, then choose “API Gateway” (2) under “Use cases for other AWS services”. And select “API Gateway” below the select box.
Then press “Next” (3).

We have just allowed API Gateway to assume the new Role.

Press “Next” again to skip the “Add permissions” page, then fill “Role name” with the desired value (i.e. “test-for-api-gateway”). Then click on “Create role”.

At this point, you must add the permission to the Role, so open the Role from the IAM Roles list, then under the Permission tab, click “Add permissions” -> “Attach policies.”

In the “Filter policy by property…”, enter S3 (1) and select for AmazonS3FullAccess (2), then click on “Attach policies.”

Mind that adding “AmazonS3FullAccess” doesn’t match the least privilege principle. So a better option could be to create a custom policy where you allow the PutObject action on the desired bucket.

We have created a role allowing an API Gateway resource method to work with S3. Open the role detail page from the Roles list and copy the ARN; this will be used in the following article when we configure an API that needs that permission to write on S3.

A more precise approach

We have said that the Role we have made is not compliant with the least privilege principle. The first thing we can do is remove the “AmazonS3FullAccess” policy and create a new one. Select the policy (1) and click “Remove” (2) and confirm if necessary. We will add a new inline policy by clicking on “Add Permissions” (3), then “Create inline policy”

Click on the JSON tab to add the policy using a JSON document.

In the editor, add the following document:

{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::test-for-api-gateway/*"
}]
}

In the bottom left corner, click on the “Review Policy” blue button, and you will see a recap view where you can set a name for the new policy.

Set a unique custom name for your policy, then click “Create policy”.

Congrats, you have just created a new role with a custom policy that allows API Gateway to write on S3!

--

--

Piero Bozzolo
Claranet-CH

Cloud Architect and developer at Claranet CH, AWS Trainer Champion