Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using Templates in Terraform

DZone's Guide to

Using Templates in Terraform

In this post we take a look at how to leverage templates in Terraform to help make your job a bit easier. Read on to find out more!

· Cloud Zone ·
Free Resource

Insight into the right steps to take for migrating workloads to public cloud and successfully reducing cost as a result. Read the Guide.

We’ve been using terraform at Zapier for over a year now and recently I was adding a new feature and looking over our large collection of IAM policy documents that are included through interpolation using the file function. One detail I noticed is that we have a lot of policies that are related to giving read only access to an S3 bucket and a single prefix and, faced with copying one and replacing the bucket name and prefix yet again I thought I’d thumb through the documentation and see if anything new has been added with this regard.

Sure enough, template_file now exists just for this feature and is actually quite easy to use. Going back to my IAM policy document example, I start by creating a template file (for us, I place this under 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"
    }
  ]
}

Here’s a complete example of using this in Terraform with a managed S3 bucket and IAM policy.

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}"
}

That’s it. Very simple tip to share but nice because it easily reduces about 10 or 15 duplicate policy documents we had laying around.

TrueSight Cloud Cost Control provides visibility and control over multi-cloud costs including AWS, Azure, Google Cloud, and others.

Topics:
terraform ,templates ,cloud ,aws s3

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}