Skip to content

S3 Bucket Policies

This guide explains how to use S3 Bucket Policies to manage access to your Amazon S3 resources. Bucket policies are JSON-based access control policies that allow you to grant or deny permissions to your S3 buckets and the objects within them.

Before you begin, you will need:

  • An active University of Oregon AWS account.
  • An existing S3 bucket. You can create one by following our Using Amazon S3 for Object Storage guide.
  • Familiarity with JSON (JavaScript Object Notation).

S3 Bucket Policies are a powerful tool for managing access to your S3 resources. They can be used to grant cross-account access, enforce encryption, and much more.

A bucket policy is a JSON document that consists of one or more statements. Each statement includes a set of permissions (Allow or Deny) for a specific principal (user, account, or service) on a specific resource (bucket or object).

  • Granting read-only access to a specific user: You can create a policy that allows a specific IAM user to read objects in your bucket, but not write or delete them.
  • Forcing encryption: You can create a policy that denies any object upload that does not include a specific type of server-side encryption.
  • Granting access to another AWS account: You can use a bucket policy to allow another AWS account to access your S3 resources.

The following Terraform code will create an S3 bucket and attach a bucket policy that grants read-only access to a specific IAM user.

# main.tf - Example for creating an S3 bucket with a read-only bucket policy
variable "read_only_user_arn" {
description = "The ARN of the IAM user to grant read-only access to"
type = string
}
resource "aws_s3_bucket" "document_storage" {
bucket = "uo-myapp-example-bucket" # Please use a long, unique name
tags = {
Name = "UO Myapp Example Bucket"
Environment = "Production"
}
}
resource "aws_s3_bucket_policy" "read_only_access" {
bucket = aws_s3_bucket.document_storage.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = ["s3:GetObject"]
Effect = "Allow"
Principal = {
AWS = var.read_only_user_arn
}
Resource = "${aws_s3_bucket.document_storage.arn}/*"
},
]
})
}
  • variable "read_only_user_arn": This defines a variable that you can use to pass the ARN of the IAM user to your Terraform configuration.
  • resource "aws_s3_bucket" "document_storage": This block declares a new S3 bucket resource.
  • resource "aws_s3_bucket_policy" "read_only_access": This block creates a new bucket policy and attaches it to the S3 bucket.
  • policy: This is the JSON document that defines the bucket policy. In this example, it grants the s3:GetObject permission to the specified IAM user for all objects in the bucket.

Now that you understand how to use S3 Bucket Policies, you can create more complex access control rules for your S3 resources.