Search code examples
amazon-s3terraformterraform-provider-aws

How do I create an S3 bucket policy from a template in Terraform 0.12?


I am trying to create an S3 bucket policy via Terraform 0.12 that will change based on environment (dev/prod). Here is a portion of the policy:

{
    "Sid": "AllowAdminAccessToBuckets",
    "Effect": "Allow",
    "Principal": "*",
    "Action": [
        "s3:GetBucket*"
    ],
    "Resource": [
        "arn:aws:s3:::${var.env-bucket}",
        "arn:aws:s3:::${var.env-bucket}/*"
    ],
    "Condition": {
        "StringEquals": {
            "aws:sourceVpce": "${var.env-vpce}"
        }
    }
}

If I do it with a JSON formatted document (not a template) the following works:

resource "aws_s3_bucket" "b" {
    bucket = "my-tf-test-bucket"
    policy = "${file("templates/policy.json")}"
}

How do I specify the variables in the policy?


Solution

  • You can use data resource to create a JSON template for policy by passing the variables based on your environment and use that template_file as policy in aws_s3_bucket resource.

    variable "env-bucket" {
      default = "sample"
    }
    variable "env-vpce" {
      default = "sample-vpc"
    }
    
    data "template_file" "policy" {
      template = "${file("policy.json")}"
    
      vars = {
        env-bucket = "${var.env-bucket}"
        env-vpce   = "${var.env-vpce}"
       }
    }
    
    resource "aws_s3_bucket" "b" {
       bucket = "my-tf-test-bucket"
       policy = "${data.template_file.policy.rendered}"
    }