How do I create an IAM role with S3 bucket access in AWS?
In this guide, we will create an IAM role with permissions to access an S3 bucket in AWS using Pulumi. This involves creating an S3 bucket, defining an IAM role, and attaching a policy to the role that grants it the necessary permissions to interact with the S3 bucket.
Key Points
- Create an S3 bucket.
- Define an IAM role with a trust policy.
- Attach an IAM policy to the role that grants S3 access.
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
// Create an S3 bucket
const bucket = new aws.s3.Bucket("my-bucket", {
acl: "private",
});
// Define the IAM role
const role = new aws.iam.Role("myRole", {
assumeRolePolicy: {
Version: "2012-10-17",
Statement: [{
Action: "sts:AssumeRole",
Principal: {
Service: "ec2.amazonaws.com",
},
Effect: "Allow",
Sid: "",
}],
},
});
// Attach a policy to the role that grants access to the S3 bucket
const policy = new aws.iam.RolePolicy("myRolePolicy", {
role: role.id,
policy: bucket.arn.apply(arn => JSON.stringify({
Version: "2012-10-17",
Statement: [{
Action: [
"s3:ListBucket",
"s3:GetObject",
"s3:PutObject",
],
Effect: "Allow",
Resource: [
arn,
`${arn}/*`,
],
}],
})),
});
// Export the bucket name and IAM role ARN
export const bucketName = bucket.bucket;
export const roleArn = role.arn;
Summary
In this guide, we created an S3 bucket and an IAM role using Pulumi. We defined a trust policy for the IAM role and attached a policy that grants the role permissions to list, get, and put objects in the S3 bucket. This setup is useful for scenarios where an EC2 instance or another AWS service needs to interact with an S3 bucket securely.
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.