ALPHY GEORGE
ALPHY GEORGE

Reputation: 131

What happens when terraform template is rendered

I came across a terraform example code regarding template_file in the below link

https://blog.james-carr.org/using-templates-in-terraform-17bb8f4a0aac

policies/s3_bucket_readonly.json.tpl

{
"Version": "2012-10-17",
"Statement": [
{
  "Action": [
    "s3:GetObject",
    "s3:ListBucket"
  ],
  "Resource": [
    "arn:aws:s3:::${bucket_name}",
    "arn:aws:s3:::${bucket_name}/${key_prefix}"
  ],
  "Effect": "Allow"
}
]
}

Terraform script

data "template_file" "cloud-trail-logs-s3-readonly" {
template = "${file("policies/s3_bucket_readonly.json.tpl")}"
vars {
    bucket_name = "${aws_s3_bucket.cloudtrail-logs.bucket}"
    key_prefix = "AWSLogs/*" 
}
}
resource "aws_s3_bucket" "cloudtrail-logs" {
bucket = "cloudtrail-logs"
acl = "private"
lifecycle_rule {
enabled = true
noncurrent_version_expiration {
  days = 30
}
}
}
resource "aws_iam_policy" "cloudtrail-logs-readonly" {
name = "prod-cloudtrail-logs-s3-readonly"
path = "/production/"
description = "Readonly access to cloudtrail-logs bucket"
policy = "${data.template_file.cloud-trail-logs-s3-readonly.rendered}"
}

Can someone explains what the ${data.template_file.cloud-trail-logs-s3-readonly.rendered} actually does ?? Does it simply apply the template variable values to the policies/s3_bucket_readonly.json.tpl and add the same as policy ?? If yes, then what does ".rendered" mean or stand for ??

Upvotes: 1

Views: 1779

Answers (1)

Baptiste Bouchereau
Baptiste Bouchereau

Reputation: 299

Yes you are right, even if your wording is inaccurate. It's the result of the template policies/s3_bucket_readonly.json.tpl after variables are applied.

Have a look at the docs (attributes reference) https://www.terraform.io/docs/providers/template/d/file.html#attributes-reference

rendered - The final rendered template.

The value of the policy will be the content of the template after terraform renders it.

After the HCL is interpreted (the terraform language is called HCL - Hashicorp Configuration Language), "${bucket_name}" will be equivalent to "${aws_s3_bucket.cloudtrail-logs.bucket}" as passed in the template resource in the vars block, and "${key_prefix}" to AWSLogs/*

I think "${aws_s3_bucket.cloudtrail-logs.bucket}" will refer to the string "cloudtrail-logs" (value of the bucket attribute in the aws_s3_bucket resource)

So the policy value should be:

{
"Version": "2012-10-17",
"Statement": [
{
  "Action": [
    "s3:GetObject",
    "s3:ListBucket"
  ],
  "Resource": [
    "arn:aws:s3:::cloudtrail-logs",
    "arn:aws:s3:::cloudtrail-logs/AWSLogs/*"
  ],
  "Effect": "Allow"
}
]
}

Upvotes: 2

Related Questions