Over a million developers have joined DZone.

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

See how the beta release of Kubernetes on DC/OS 1.10 delivers the most robust platform for building & operating data-intensive, containerized apps. Register now for tech preview.

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": [
      "Resource": [
      "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.

New Mesosphere DC/OS 1.10: Production-proven reliability, security & scalability for fast-data, modern apps. Register now for a live demo.

terraform ,templates ,cloud ,aws s3

Published at DZone with permission of James Carr, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}