How do Interpolate a terraform resource reference with a string?

Viewed 13

In terraform I create an S3 bucket like so:

resource "aws_s3_bucket" "test_bucket" {

bucket = "my-test-bucket"

}

In terraform I have declared an iam policy resource like this (this is where I'm wrong btw):

resources = ["aws_s3_bucket.test_bucket.arn/AWSLogs/${var.account_id}/*"]

Terraform plan, rightfully shows:

+ Resource  = "aws_s3_bucket.test_bucket.arn/AWSLogs/123456789101/*"

How can I get terraform plan to show/interpolate/build the following string?:

+ Resource  = "arn:aws:s3:::my-test-bucket/AWSLogs/123456789101/*"
1 Answers

Since you have seen that the output of this:

resources = ["aws_s3_bucket.test_bucket.arn/AWSLogs/${var.account_id}/*"]

is:

+ Resource  = "aws_s3_bucket.test_bucket.arn/AWSLogs/123456789101/*"

the conclusion that should be derived is that this is a string literal. In other words, Terraform is treating it as a regular string. Since you have this:

resource "aws_s3_bucket" "test_bucket" {

bucket = "my-test-bucket"

}

The way to construct the string you want is to use the proper interpolation:

"${aws_s3_bucket.test_bucket.arn}/AWSLogs/123456789101/*"

Make sure you understand how to access attributes and arguments that resources provide [1]. In your case, you are looking for attribute exported by the S3 resource [2].


[1] https://developer.hashicorp.com/terraform/language/expressions/references

[2] https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket#attributes-reference

Related