Bootstrap FreeKB - Amazon Web Services (AWS) - Add Policy to an S3 Bucket using Terraform
Amazon Web Services (AWS) - Add Policy to an S3 Bucket using Terraform


A policy grants certain permissions to certain resources. For example, one such policy would be to allow an Elastic Load Balancer to write logs to the S3 Bucket.

An S3 Bucket is similar to an NFS share in that it is a mountable storage volume.

Let's say you have the following files on your Terraform server.

├── required_providers.tf
├── s3_buckets (directory)
│   ├── provider.tf
│   ├── buckets.tf

 

required_providers.tf will almost always have this.

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
    }
  }
}

 

Let's say provider.tf in the network_load_balancer directory has the following. In this example, the "default" profile in /home/username/.aws/config and /home/username/.aws/credentials is being used. This assumes you have setup Terraform as described in Amazon Web Services (AWS) - Getting Started with Terraform.

provider "aws" {
  alias   = "default"
  profile = "default"
  region  = "default"
}

 

And let's say buckets.tf contains something like this to create a bucket named my_bucket_fjfnv9d3d9 and to give full access to the bucket for root and user john.doe.

resource "aws_s3_bucket" "my_bucket_fjfnv9d3d9" {
  bucket = "my-bucket-fjfnv9d3d9"

  tags = {
    Name        = "my-bucket-fjfnv9d3d9"
    Environment = "staging"
  }
}

resource "aws_s3_bucket_policy" "allow_root" {
  bucket = aws_s3_bucket.my_bucket_fjfnv9d3d9.id
  policy = data.aws_iam_policy_document.allow_root.json
}

data "aws_iam_policy_document" "allow_root" {
  statement {
    principals {
      type        = "AWS"
      identifiers = ["arn:aws:iam::123456789012:root", "arn:aws:iam::123456789012:user/john.doe"]
    }

    actions = [
      "s3:*",
    ]

    resources = [
      aws_s3_bucket.my_bucket_fjfnv9d3d9.arn,
      "${aws_s3_bucket.my_bucket_fjfnv9d3d9.arn}/*",
    ]
  }
}

 

You may need to run the terraform init command.

terraform init

 

The terraform plan command can be used to see what Terraform will try to do.

terraform plan

 

And the terraform apply command can be used to create the S3 Bucket.

terraform apply

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter fe1cfc in the box below so that we can be sure you are a human.