Metro
Metro

Reputation: 975

Terraform Variables Not Being Expanded

I have a json file bucketPolicy.json

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "s3:DeleteBucket"
      ],
      "Effect": "Deny",
      "Resource": "arn:aws:s3:::$${aws_s3_bucket.destination.id}",
      "Principal": {
        "AWS": ["*"]
      }
    }
  ]
}

And I've created a template_file as such

data "template_file" "test" {
  template = file("./templates/destinationBucketPolicy.json")
  vars = {
    (aws_s3_bucket.destination.id) = var.destination_bucket_name

  }
}

But when I try to use this for my bucket policy

resource "aws_s3_bucket_policy" "destination" {
  bucket = aws_s3_bucket.destination.id

  policy = data.template_file.test.rendered
}

The value for var.destination_bucket_name does not not get expanded into the policy, instead it appears literally as "Resource": "arn:aws:s3:::${aws_s3_bucket.destination.id}"

Is there a way to get this to expand so that it picks up the actual value for the variable?

Upvotes: 2

Views: 555

Answers (1)

Marcin
Marcin

Reputation: 238081

These days its better to use templatefile:

locals {
  test = templatefile("${path.module}/destinationBucketPolicy.json",
             {
                 bucket_name = var.destination_bucket_name
             })
}

with template of:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "s3:DeleteBucket"
      ],
      "Effect": "Deny",
      "Resource": "arn:aws:s3:::${bucket_name}",
      "Principal": {
        "AWS": ["*"]
      }
    }
  ]
}

Upvotes: 3

Related Questions