Secrets Management in Terraform
6 min read
Welcome back, infrastructure architect! 🏗️
So far, you’ve learned how to build servers, configure networks, and spin up databases. But today, we need to talk about the most anxiety-inducing part of DevOps: Secrets.
We are talking about database passwords, API keys, private certificates, and that specific string of characters that, if leaked, would allow a hacker to mine crypto on your company's credit card while you sleep. 💸
Let’s lock things down.
1. The Danger Zone: Why You Shouldn't Hardcode Secrets 🚫
The Definition
Hardcoding refers to the practice of embedding data (like passwords or keys) directly into the source code of a program or configuration file.
The Problem
Imagine writing your credit card number on a sticky note and putting it on your office window. That is essentially what you do when you write password = "SuperSecret123" inside a .tf file.
Here is the chain of catastrophe:
- You type the password in
main.tf. - You run
git add .andgit commit. - You push to GitHub/GitLab.
- Game Over. Even if the repo is private, that password is now in the commit history forever. If you make the repo public later, bots scraping GitHub will find that key within seconds (literally seconds) and compromise your account.
🧪 Practical Example: The "Oops" Moment
DON'T DO THIS:
resource "aws_db_instance" "default" {
allocated_storage = 10
engine = "mysql"
instance_class = "db.t3.micro"
name = "mydb"
username = "admin"
# 🚩 DANGER: This is hardcoded!
password = "my-password-123"
}Fun Fact: There are automated bots that scan public GitHub repositories specifically looking for text patterns like
AWS_ACCESS_KEY_ID. In 2019, a developer accidentally uploaded AWS keys and woke up to a $65,000 bill because hackers spun up hundreds of massive instances for crypto mining. Don't be that developer.
2. Using Environment Variables (TF_VAR) 🛡️
The Concept
Environment variables are dynamic values that can affect the way running processes will behave on a computer. Terraform is programmed to look for specific environment variables on your machine to populate input variables.
How It Solves the Problem
By keeping the secret in your computer's temporary memory (the shell session) rather than the file, the secret never gets written to main.tf or pushed to Git.
🔧 Hands-On Implementation
Terraform automatically looks for environment variables that start with TF_VAR_ followed by your variable name.
Step 1: Declare the variable in Terraform (empty)
In your variables.tf:
variable "db_password" {
description = "The password for the database"
type = string
# No default value here!
}Step 2: Reference it in your resource
In your main.tf:
resource "aws_db_instance" "default" {
# ... other config ...
password = var.db_password
}Step 3: Feed the value from your terminal
In your terminal (Bash/Zsh):
export TF_VAR_db_password="CorrectHorseBatteryStaple"
terraform applyIndustry Standard: In CI/CD pipelines (like GitHub Actions or Jenkins), you store these secrets in the pipeline's "Secrets" settings. During the build, the pipeline injects them as environment variables.
3. Marking Variables and Outputs as Sensitive 🙈
The Problem
You solved the Git hardcoding issue using Env Vars. Great! But watch what happens when you run terraform plan:
Terraform will perform the following actions:
+ resource "aws_db_instance" "default" {
...
+ password = "CorrectHorseBatteryStaple"
...
}Terraform just printed your secret in plain text in the logs! 🤦♂️ If you are running this in a shared CI/CD pipeline, anyone reading the build logs can see it.
The Solution: sensitive = true
This boolean flag tells Terraform: "Use this value, but do not print it to the CLI output."
🔧 Hands-On Implementation
Masking Input Variables:
variable "db_password" {
description = "The password for the database"
type = string
sensitive = true # <--- The Magic Flag
}Now, when you run terraform plan, you see:
+ password = (sensitive value)Masking Outputs:
If you want to output the database endpoint or password (to pass to another module), Terraform will yell at you if you don't mark the output as sensitive too.
output "db_password" {
value = aws_db_instance.default.password
sensitive = true
}Crucial Warning:
sensitive = trueis a UI feature. It hides the value from the terminal output. It does NOT encrypt the value in the Terraform State file. If someone opens yourterraform.tfstatefile, the password is there in plain text. (We solve this by encrypting the Remote State bucket—a topic for another guide, but keep it in mind!).
4. Integrating with Secret Managers (AWS Secrets Manager) 🔐
The Concept
A Secret Manager is a cloud service dedicated to storing, rotating, and retrieving secrets securely. Examples include AWS Secrets Manager, Azure Key Vault, Google Secret Manager, and HashiCorp Vault.
The Problem
Environment variables are great, but managing them across 50 developers and 200 microservices is a nightmare. What if you need to rotate the password? Do you ask 50 developers to update their .bashrc file? No.
The Solution
Store the secret in AWS Secrets Manager, and have Terraform fetch it dynamically using a data source.
🔧 Hands-On Implementation (AWS)
Let's assume you have manually created a secret in AWS Secrets Manager named production/db/password with a key-value pair: {"password": "super-secure-pass"}.
Step 1: Fetch the Secret using a Data Source
Terraform doesn't create the secret here; it just reads it.
data "aws_secretsmanager_secret" "db_secret" {
name = "production/db/password"
}
data "aws_secretsmanager_secret_version" "db_secret_ver" {
secret_id = data.aws_secretsmanager_secret.db_secret.id
}Step 2: Parse and Use the Secret
AWS stores secrets as a JSON string. We need to decode it.
locals {
# Parse the JSON string into a map
db_creds = jsondecode(data.aws_secretsmanager_secret_version.db_secret_ver.secret_string)
}
resource "aws_db_instance" "default" {
# ...
username = "admin"
password = local.db_creds.password
}Why is this the Industry Standard?
- Centralization: One place to manage secrets.
- Rotation: AWS can automatically change the password every 30 days. Terraform just picks up the new one on the next run.
- Audit: You can see exactly who accessed the secret and when.
Brief Mention: HashiCorp Vault
You might hear about Vault. It is the "Rolls Royce" of secret management. It’s cloud-agnostic and incredibly powerful (it can generate temporary AWS credentials that expire in 15 minutes). However, it requires more setup than AWS Secrets Manager. If you are just starting, stick to the cloud-native manager first.
🧩 Summary checklist
- Never type a password in a
.tffile. - Use
TF_VAR_variable_namefor local development. - Always add
sensitive = trueto variable definitions for secrets. - For production, fetch secrets dynamically from a Secret Manager using
datasources. - Bonus: Ensure your
terraform.tfstateis stored remotely (like S3) and encrypted, because that's the only place secrets still exist in plain text.
Stay safe out there! 🕵️♂️
📚 References & Further Reading
- Terraform Input Variables (Sensitive Data):
https://developer.hashicorp.com/terraform/language/values/variables#suppressing-values-in-cli-output - Terraform & Environment Variables:
https://developer.hashicorp.com/terraform/cli/config/environment-variables - AWS Secrets Manager with Terraform:
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/secretsmanager_secret_version - Security in Terraform (State File):
https://developer.hashicorp.com/terraform/language/state/sensitive-data
Challenge
Challenge: Securely Fetch and Output a Secret from AWS Secrets Manager
Your task is to write a Terraform configuration that retrieves a secret from AWS Secrets Manager, parses its JSON content, and then exposes a specific value from that secret as a sensitive output.
The secret stored in AWS Secrets Manager has a JSON structure like this: {"db_username": "admin_user", "db_password": "a-very-secure-password!"}.
Requirements:
- Define a
datasource foraws_secretsmanager_secret_versionto fetch the latest version of the secret. Give the data source a local name ofdb_creds. - Use the input variable
secret_arnto specify which secret to fetch. - The secret's value is a JSON string located in the
secret_stringattribute of the data source. - Create an output named
database_password. - The value for this output must be the
db_passwordextracted from the parsed JSON secret. - Crucially, you must ensure that the
database_passwordoutput is marked assensitiveto prevent its value from being printed in Terraform's console output.
Expected result
Your final configuration should contain a data block and an output block.
Specifically:
- A
data "aws_secretsmanager_secret_version" "db_creds"block that usesvar.secret_arnfor itssecret_id. - An
output "database_password"block. - The
valueof the output must correctly use thejsondecode()function to parsedata.aws_secretsmanager_secret_version.db_creds.secret_stringand access thedb_passwordkey. - The output block must contain the line
sensitive = true.