Terraform: Cross Account S3 Bucket Access Control

Whilst auditing a set of organizational AWS accounts, I wanted to consolidate operational S3 buckets into a single account and grant access as required. It might not be immediately obvious the first time you do this, so this post is a bit of a primer on cross-account S3 access control, and implementing such with Terraform.

Connecting a remote IAM principle to an S3 bucket involves two distinct steps. First you create a trust relationship with the remote AWS account by specifying the account ID in the S3 bucket policy. Lastly, the remote AWS account may then delegate access to its IAM users (or roles) by specifying the bucket name in a policy. Because the S3 namespace is global, policies in the remote account can resolve the bucket by name.

The S3 bucket policy might look something like this.

In this example, read-only access to the bucket the-private-bucket is delegated to the AWS account 123456789012. The specific principal referenced is the root user of that account, but this is effective for any IAM user/role on that account having access specifically granted via an IAM policy.

Such an IAM policy might look something like this.

Remember this policy should be defined on the remote (delegated) AWS account, and thus attached to any IAM principal in that account where access is being granted.

After proving your setup by testing out your variation of the above policies, you can model this with Terraform. By defining both AWS accounts as Terraform providers, you can have Terraform manage this for you end-to-end. For completeness, my example below includes both AWS providers for the host and demo accounts, the creation of the S3 bucket, an IAM user and role, and definition & attachment of both policies.