Over a million developers have joined DZone.

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

Download this eBook outlining the critical components of success for SaaS companies - and the new rules you need to play by.  Brought to you in partnership with NuoDB.

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.

Learn how moving from a traditional, on-premises delivery model to a cloud-based, software-as-a-service (SaaS) strategy is a high-stakes, bet-the-company game for independent software vendors. Brought to you in partnership with NuoDB.

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.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}