To set up an IAM role for an EC2 instance to access an S3 bucket, you need to create an IAM role with the necessary permissions and then associate that role with the EC2 instance.
-
Create the IAM Role:
- Go to the IAM console.
- Choose "Roles" and then "Create role."
- Choose "AWS service" and then "EC2" as the trusted entity.
- Attach the policy with S3 access, e.g., AmazonS3ReadOnlyAccess.
-
Attach the IAM Role to the EC2 Instance:
- Go to the EC2 console.
- Select the instance and choose "Actions" > "Security" > "Modify IAM Role."
- Select the newly created IAM role and apply it.
Example IAM Policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:*",
"Resource": "arn:aws:s3:::example-bucket/*"
}
]
}
Example Code to Access S3 from EC2 Instance:
import boto3
s3 = boto3.client('s3')
response = s3.list_objects_v2(Bucket='example-bucket')
for obj in response['Contents']:
print(obj['Key'])