← Back to list

Terraform templating

Improve IaC readability, maintainability.

Software Is Just Lego · 2026-03-11 04:36 · 0 claps · 1.0 min read
#terraform #templating #aws #devops #infrastructure-as-code
Open on Medium ↗
Wiki topics: ☁️ · DevOps & Cloud

Terraform templating

Improve IaC readability, maintainability.

The what and the why

In a previous article, I deployed an EC2 to AWS to demonstrate terraform modules. In the EC2 block, I defined a user_data script inline:

module "ec2" {
    ...
    user_data = <<EOF
#!/bin/bash
SECRET_ARN=${data.aws_secretsmanager_secret.db_password.arn}
echo "DB_PASSWORD=$(aws secretsmanager get-secret-value --secret-id $SECRET_ARN --query SecretString --output text)" >> /etc/app.env
EOF
    ...
}

This works, but looks messy and becomes hard to understand or maintain as userdata scripts grow.

Terraform templating exists to solve this problem. It allows us to keep scripts and variables separate at runtime.

Using terraform templating

.tfpl file

We extract the inline contents of the userdata script into a new file named userdata.sh.tftpl. The .tftpl file extension is a useful convention that tells us this is a template file. This file only contains one variable to be substituted: the secret ARN.

#!/bin/bash
echo "DB_PASSWORD=$(aws secretsmanager get-secret-value --secret-id ${secret_arn} --query SecretString --output text)" >> /etc/app.env

As before, the ${} syntax implies the variable will be substituted by terraform.

Usage with templatefile()

module "ec2" {
    ...
    user_data = templatefile("${path.module}/userdata.sh.tftpl", {
        secret_arn = data.aws_secretsmanager_secret.db_password.arn
    })
    ...
}

Notes:

  • $path.module is a builtin terraform expression that returns the path of the directory containing the current .tf file.
  • The templatefile function outputs a string, it doesn’t actually change the template file on the filesystem.
  • The first argument to templatefile is the file itself
  • The second argument is a map of variables

Conclusion

Terraform templating is incredibly useful to make your IaC projects more readable and maintainable, especially when you want to configure infrastructure differently across environments. Use well!

Catch you in the next one.


메타데이터
post_id
897fc9130bc1
slug
terraform-templating-897fc9130bc1
url
https://medium.com/@softwareisjustlego/terraform-templating-897fc9130bc1
canonical_url
https://medium.com/@softwareisjustlego/terraform-templating-897fc9130bc1
author_url
https://medium.com/@softwareisjustlego
status
ok
fetched_at
2026-06-28 10:39:35