How to access S3 from EC2 Instance using IAM role

An application running on EC2 instance that needs access to S3 requires credentials. You can distribute credentials to the app during deployment but it is not a secure design and Amazon discourages distributing credentials. Instead, you can use roles to grant privileges to AWS resources. Roles do not have long term credentials making it secure.

To create a role, login to the AWS Management console and select IAM. In the IAM dashboard select Roles and choose Create role.

Now select the AWS service(EC2 in our scenario) that you would like to grant the role to and choose Next: Permissions.

Choose the policy that you would like to attach to the role. I want my EC2 Instance to be able to have full access to S3. Hence I selected the AmazonS3FullAccess. Choose Next: Tags to add tags to the role.

Adding tags to any AWS service is optional. Choose Next:Review

Enter a value for the Role name and choose Create role. I named my role as ec2-to-s3.

On the services page, choose EC2 to open the EC2 dashboard and right click on the instance that you would like to attach the role to and choose Attach/Replace IAM Role under Instance Settings.

Select the ec2-to-s3 role that you have previously created and choose Apply.

The ec2-to-s3 role has been attached to the EC2 Instance. With this role attached, the EC2 Instance now has full access to the S3 resources.

To test the functionality of the role, SSH into the EC2 instance and type the command aws s3 ls to list all the buckets in your Amazon account.