We close the chapter on environment management by looking in detail at how values are passed to Terraform: .tfvars files and environment variables. We’ve already mentioned them in passing; now you’ll fully understand how to separate configuration (the values that change) from code (the logic that stays the same). This separation is key to managing environments cleanly.

Reminder: Variables

Remember the variables from Chapter 10. A variable is a “placeholder” in your code that gets filled with a value from outside:

variable "tipo_instancia" {
  description = "EC2 instance type"
  type        = string
}

variable "cantidad_servidores" {
  type    = number
  default = 1
}

The code uses var.tipo_instancia, but does not set the value. Where does that value come from? There are several ways to provide it, and we’ll see them here.

.tfvars Files: The Main Method

A .tfvars file is a file where you assign values to variables. It’s the most common and organized way to configure an environment. For example:

# produccion.tfvars
tipo_instancia      = "t3.large"
cantidad_servidores = 5
nombre_proyecto     = "tienda-prod"
# desarrollo.tfvars
tipo_instancia      = "t3.micro"
cantidad_servidores = 1
nombre_proyecto     = "tienda-dev"

Notice the key idea: the code is the same, but each .tfvars file gives it different values. This is exactly what allows you to use the same logic for multiple environments (subchapter 19.2).

How to Use a .tfvars

You tell Terraform which values file to use with the -var-file option:

terraform apply -var-file="produccion.tfvars"   # applies with production values
terraform apply -var-file="desarrollo.tfvars"   # applies with development values

Special case — terraform.tfvars: if you name a file exactly terraform.tfvars, Terraform loads it automatically without you having to specify it. That’s why, in the directory strategy (subchapter 19.2), each environment folder usually has its own terraform.tfvars that is applied automatically.

Analogy: Terraform code is like a letter template with blanks (“Dear ___, your order ___ is ready”). The .tfvars files are the data that fill in the blanks for each recipient. One template, many personalized letters. You change the data, not the template.

Environment Variables: Another Way to Pass Values

Another way to provide values to variables is through operating system environment variables, using the TF_VAR_ prefix:

TF_VAR_tipo_instancia = "t3.micro"

Terraform automatically reads any environment variable that starts with TF_VAR_ and assigns it to the corresponding variable (here, tipo_instancia).

When is this used? Mainly in two cases:

  • In automation (CI/CD, Chapter 22): automated systems often pass values as environment variables, without files.
  • For sensitive data (secrets): as we’ll see shortly, passwords and keys should not go in .tfvars files that are pushed to Git; environment variables are a way to pass them without writing them in any repository file.

The Order of Precedence

Since there are several ways to provide values, Terraform follows an order of precedence if the same value is defined in multiple places (from lowest to highest priority, roughly):

1. "default" value in the variable definition   (lowest)
2. terraform.tfvars file (automatic)
3. -var-file files you specify
4. TF_VAR_ environment variables
5. -var option on the command line              (highest)

You don’t need to memorize it, but remember: if you define a value in several places, the most specific/direct one wins. If in doubt, what you put on the command line overrides everything else.

⚠️ Security: Never Put Secrets in Versioned .tfvars

This is critical. Your .tfvars files with normal configuration (sizes, names) can be safely stored in Git. But you should NEVER put sensitive data —database passwords, API keys, tokens— in .tfvars files that you push to the repository. If you do, those secrets are exposed in the Git history to anyone who accesses it.

❌ BAD:  password = "MyPassword123" in a .tfvars file pushed to Git
✅ GOOD: the secret is passed via environment variable, or better yet,
         read from a secrets manager (Secrets Manager, Ch. 23)

The correct ways to handle secrets:

  • Environment variables (TF_VAR_password), which are not stored in any repo file.
  • Secrets managers like AWS Secrets Manager or Parameter Store (which we’ll see in Chapter 23): Terraform reads them at runtime, so the secret is never written in the code.
  • Add .tfvars files with secrets to .gitignore so they are never pushed.

Also remember (from Chapter 11) that the state itself can contain sensitive data, so the remote backend must be encrypted and access-restricted. Secret management is a serious topic that we’ll revisit in depth in Chapter 23.

What You Should Remember

  • Variables leave “blanks” in the code; values are provided from outside, separating configuration from code (the same logic works for multiple environments).
  • .tfvars files are the main way to assign values; you use -var-file="environment.tfvars", and a file named terraform.tfvars is loaded automatically.
  • Environment variables with the TF_VAR_ prefix are another way to pass values, useful in CI/CD and for secrets.
  • There is an order of precedence when a value is defined in multiple places: the most direct wins (command line > environment > files > default).
  • ⚠️ Critical security: never put secrets (passwords, keys) in .tfvars files versioned in Git. Use environment variables, secrets managers (Secrets Manager, Chapter 23), and .gitignore.

You’ve finished Chapter 19! You now know how to manage multiple environments cleanly and securely. In Chapter 20 we’ll dive deeper into one of the most important topics for teamwork: remote backends and state locking.

Cloud, AWS & Terraform — From Zero to Expert

Chapter 1 · What is cloud computing

Chapter 2 · The cloud market and major providers

Chapter 3 · Regions, availability zones and edge

Chapter 4 · Compute: EC2

Chapter 5 · Storage: S3

Chapter 6 · Networking: VPC

Chapter 7 · Identity and access: IAM

Chapter 8 · Managed databases

Chapter 9 · Why Infrastructure as Code

Chapter 10 · HCL: the Terraform language

Chapter 11 · Providers and state

Chapter 12 · Your first real infrastructure in Terraform

Chapter 13 · Load balancing and auto scaling

Chapter 14 · Serverless with Lambda

Chapter 15 · Messaging and events

Chapter 16 · Content delivery and DNS

Chapter 17 · Containers on AWS

Chapter 18 · Modules: reuse and composition

Chapter 19 · Workspaces and environment management

Chapter 20 · Remote backends and locking

Chapter 21 · Infrastructure testing

Chapter 22 · Terraform in CI/CD

Chapter 23 · Defense in depth

Chapter 24 · Observability: logs, metrics and traces

Chapter 25 · Cost optimization

Chapter 26 · High availability and disaster recovery

Chapter 27 · AWS Well-Architected Framework

Chapter 28 · Serverless architectures at scale

Chapter 29 · Data platforms on AWS

Chapter 30 · Multi-account and landing zones

Chapter 31 · Platform Engineering and Internal Developer Platform

Chapter 32 · Relevant AWS certifications

Chapter 33 · Projects to consolidate what you've learned

Chapter 34 · Resources and community

© Copyright 2024. All rights reserved