1. Answers
  2. Managing AWS S3 Bucket Using IAM

How do I manage an AWS S3 bucket using IAM?

In this guide, we will create an S3 bucket and an IAM role with a policy that grants permissions to access the S3 bucket. This setup is useful for controlling access to your S3 buckets using IAM roles and policies.

import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";

// Create an S3 bucket
const bucket = new aws.s3.Bucket("my-bucket");

// Create an IAM role
const role = new aws.iam.Role("my-role", {
    assumeRolePolicy: JSON.stringify({
        Version: "2012-10-17",
        Statement: [{
            Action: "sts:AssumeRole",
            Principal: {
                Service: "ec2.amazonaws.com",
            },
            Effect: "Allow",
            Sid: "",
        }],
    }),
});

// Create an IAM policy for the S3 bucket
const bucketPolicy = new aws.iam.Policy("my-bucket-policy", {
    policy: bucket.arn.apply(arn => JSON.stringify({
        Version: "2012-10-17",
        Statement: [{
            Action: [
                "s3:ListBucket",
                "s3:GetObject",
                "s3:PutObject",
            ],
            Effect: "Allow",
            Resource: [
                arn,
                `${arn}/*`,
            ],
        }],
    })),
});

// Attach the policy to the role
const rolePolicyAttachment = new aws.iam.RolePolicyAttachment("my-role-policy-attachment", {
    role: role.name,
    policyArn: bucketPolicy.arn,
});

// Export the bucket name and role ARN
export const bucketName = bucket.bucket;
export const roleArn = role.arn;

Key Points

  • We created an S3 bucket using aws.s3.Bucket.
  • We created an IAM role using aws.iam.Role with a trust policy allowing EC2 instances to assume the role.
  • We created an IAM policy using aws.iam.Policy that grants permissions to list, get, and put objects in the S3 bucket.
  • We attached the policy to the role using aws.iam.RolePolicyAttachment.

Summary

In this guide, we demonstrated how to manage an AWS S3 bucket with IAM by creating an S3 bucket, an IAM role, a policy granting access to the bucket, and attaching the policy to the role using Pulumi. This setup ensures controlled access to the S3 bucket using IAM roles and policies.

Deploy this code

Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.

Sign up

New to Pulumi?

Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.

Sign up