πŸ“˜ Terraform Environment Variables: Securely Passing Sensitive Data

When working with Terraform, we often deal with sensitive data like API keys, database passwords, or cloud provider credentials. Hardcoding these values in .tf files is unsafe because:

  • They may leak in Git repositories.
  • They could be visible to team members unintentionally.
  • They can expose security vulnerabilities.

πŸ‘‰ The solution? Terraform Environment Variables

Terraform allows us to inject values into variables through environment variables in a secure and flexible way.

This approach ensures that secrets never appear in the code itself but are instead supplied at runtime.


πŸ”‘ What Are Terraform Environment Variables?

In Terraform, environment variables are OS-level variables that Terraform reads automatically. They can be used to:

  1. Pass sensitive data (like API keys, passwords).
  2. Set default values without modifying .tf files.
  3. Configure providers securely.

Terraform recognizes variables with a specific prefix:

  • TF_VAR_name β†’ Maps directly to a Terraform variable.
  • Example: TF_VAR_db_password=mysecretpassword

πŸ–₯️ 3 Example Programs for Terraform Environment Variables


βœ… Example 1: Passing AWS Credentials Securely

Step 1: Define variables

variable "aws_access_key" {
type = string
sensitive = true
}
variable "aws_secret_key" {
type = string
sensitive = true
}

Step 2: Provider using variables

provider "aws" {
region = "us-east-1"
access_key = var.aws_access_key
secret_key = var.aws_secret_key
}

Step 3: Set environment variables

Terminal window
export TF_VAR_aws_access_key="AKIAXXXXXX"
export TF_VAR_aws_secret_key="abcd1234secret"

πŸ‘‰ Now run terraform apply without exposing keys in .tf files.


βœ… Example 2: Database Password with Environment Variables

Step 1: Define variable

variable "db_password" {
type = string
sensitive = true
}

Step 2: Use in resource

resource "aws_db_instance" "mydb" {
identifier = "mydb"
engine = "mysql"
username = "admin"
password = var.db_password
instance_class = "db.t3.micro"
allocated_storage = 20
}

Step 3: Export environment variable

Terminal window
export TF_VAR_db_password="StrongP@ssw0rd!"

πŸ‘‰ Database password never appears in code, only injected at runtime.


βœ… Example 3: Using Environment Variables for Custom Tags

Step 1: Define variable

variable "environment" {
type = string
}

Step 2: Apply to resource

resource "aws_s3_bucket" "bucket" {
bucket = "env-variable-example"
tags = {
Environment = var.environment
}
}

Step 3: Export variable

Terminal window
export TF_VAR_environment="production"

πŸ‘‰ The S3 bucket gets a tag Environment=production without modifying .tf files.


🧩 Advantages of Terraform Environment Variables

  1. Security First – Secrets are not stored in .tf files or Git repos.
  2. Flexibility – Easily switch between environments (dev, test, prod).
  3. Automation – Works seamlessly in CI/CD pipelines.
  4. Best Practice – Industry standard for secret management.
  5. Reduced Errors – Avoids accidental exposure of sensitive data.

πŸ“– Real-World Use Cases

  1. Cloud Provider Authentication – AWS, Azure, GCP credentials.
  2. Database Configurations – Securely pass passwords.
  3. Application Secrets – API keys, tokens, OAuth credentials.
  4. Environment-Specific Configs – dev vs prod differences.
  5. CI/CD Pipelines – Store environment variables in GitHub Actions, Jenkins, GitLab.

🧠 How to Remember Environment Variables (Exam & Interview Prep)

πŸ‘‰ Use this Mnemonic: β€œTF_VAR = Terraform Variable”

  • Prefix every variable with TF_VAR_.
  • Example: TF_VAR_password=secret123 β†’ maps to variable "password" {}.

Another trick:

  • ENV = External, Not Visible β†’ Think environment variables are external inputs, not visible in code.

🎯 Why Is It Important to Learn This Concept?

  • For Security β†’ Never expose secrets in .tf files.
  • For Exams β†’ Terraform Associate Certification often asks how to handle sensitive data.
  • For Teams β†’ Developers can collaborate without sharing sensitive credentials.
  • For Real Projects β†’ Essential in pipelines, where environment variables are injected dynamically.

Without environment variables:

  • Passwords may leak in Git.
  • Terraform code becomes less reusable.
  • Security audits fail.

With environment variables:

  • Secrets stay safe.
  • Code is reusable.
  • Industry best practices are followed.

πŸ–₯️ More Examples


βœ… Example 4: Multiple Variables with One Export

Terminal window
export TF_VAR_region="us-west-2"
export TF_VAR_instance_type="t2.micro"
export TF_VAR_owner="DevTeam"

πŸ‘‰ Terraform automatically maps these to variables.


βœ… Example 5: Using Environment Variables in CI/CD

# GitHub Actions Example
env:
TF_VAR_db_password: ${{ secrets.DB_PASSWORD }}
TF_VAR_api_key: ${{ secrets.API_KEY }}
steps:
- name: Terraform Apply
run: terraform apply -auto-approve

πŸ‘‰ Environment variables come directly from GitHub Secrets.


βœ… Example 6: Overriding Defaults with Env Vars

variable "region" {
type = string
default = "us-east-1"
}

If you run:

Terminal window
export TF_VAR_region="eu-west-1"
terraform apply

πŸ‘‰ The default (us-east-1) is overridden with "eu-west-1".


πŸ“Š Comparison: Hardcoded Secrets vs Environment Variables

FeatureHardcoded SecretsEnvironment Variables
Security RiskHigh (secrets in code)Low (secrets external)
FlexibilityLowHigh
Version Control SafetyUnsafe (committed)Safe (not in Git)
Best PracticeβŒβœ…
CI/CD UsageDifficultStandard

🧠 Interview & Exam Preparation

Typical Questions:

  1. Q: How can you securely pass a database password to Terraform? A: By exporting TF_VAR_db_password="mypassword" as an environment variable.

  2. Q: What prefix must Terraform environment variables have? A: TF_VAR_ followed by the variable name.

  3. Q: Why are environment variables preferred over hardcoding values? A: They protect sensitive data and improve reusability.


πŸ† Conclusion

Terraform Environment Variables are a secure, flexible way to pass sensitive data into Terraform configurations.

  • They keep secrets out of code.
  • They work seamlessly in local setups and CI/CD pipelines.
  • They ensure security best practices are followed.

πŸ‘‰ Key Takeaway: Always use environment variables for secrets. Never hardcode them in .tf files.