T O P

  • By -

rplrd

If you're trying to use a variable in a json (not .tf) is file, you can't. Files are passed as-is. You can easily work around that by using a template_file resource https://www.terraform.io/docs/providers/template/d/file.html


Kratisto78

Are you trying to call it using your full name? Example below resource "aws_s3_bucket_policy" "b" { bucket = "${aws_s3_bucket.b.id}" policy = <


crapspakkle

This is what I have so far: https://pastebin.com/SZy6Gu5U


Kratisto78

What do you want to be able to access the bucket? A lambda?


crapspakkle

Going to be used to store various audit logs


dru2691

If this is exactly what you have, you are missing a `]` and a closing `}` at the end of that policy.


crapspakkle

No I snipped part of it to show the block with the arn for the Resource


apparentlymart

Because IAM policies are JSON, it's easiest to just build a data structure representing the policy you want and let Terraform itself do the JSON encoding. For example: ``` resource "aws_s3_bucket_policy" "example" { # ... policy = jsonencode({ "Version": "2012-10-17", "Id": "example", "Statement": [ { # (whatever other properties you want to set) "Resource": "arn:aws:s3:::${aws_s3_bucket.example.bucket}", } ], }) } ``` If having it in a separate file in JSON format is important in your case, you can do something like what you were trying using the `templatefile` function, which allows treating an external file as a Terraform template with some provided variables: ``` resource "aws_s3_bucket_policy" "example" { # ... policy = templatefile("${path.module}/policy.json.tmpl", { bucket_name = aws_s3_bucket.example.bucket }) } ``` Inside the `policy.json.tmpl` file you can use `${bucket_name}` to interpolate the bucket name that's passed in in the map in the second argument. `templatefile` does simple string templating, so in this case it's your responsibility to ensure that the result of the template is valid JSON. I'd recommend using `jsonencode` with an inline object value instead if possible, because then the result is guaranteed to be valid JSON without any special templating effort. In earlier versions of Terraform the `template_file` data source might've been used instead of `templatefile` here, but the data source is deprecated for this sort of use in Terraform 0.12 and later; the `templatefile` function is its replacement.