Learn Terraform · 9/11

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:

  1. You type the password in main.tf.
  2. You run git add . and git commit.
  3. You push to GitHub/GitLab.
  4. 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:

hcl
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:

hcl
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:

hcl
resource "aws_db_instance" "default" {
  # ... other config ...
  password = var.db_password
}

Step 3: Feed the value from your terminal
In your terminal (Bash/Zsh):

bash
export TF_VAR_db_password="CorrectHorseBatteryStaple"
terraform apply

Industry 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:

text
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:

hcl
variable "db_password" {
  description = "The password for the database"
  type        = string
  sensitive   = true  # <--- The Magic Flag
}

Now, when you run terraform plan, you see:

text
  + 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.

hcl
output "db_password" {
  value     = aws_db_instance.default.password
  sensitive = true
}

Crucial Warning: sensitive = true is 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 your terraform.tfstate file, 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.

hcl
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.

hcl
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?

  1. Centralization: One place to manage secrets.
  2. Rotation: AWS can automatically change the password every 30 days. Terraform just picks up the new one on the next run.
  3. 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

  1. Never type a password in a .tf file.
  2. Use TF_VAR_variable_name for local development.
  3. Always add sensitive = true to variable definitions for secrets.
  4. For production, fetch secrets dynamically from a Secret Manager using data sources.
  5. Bonus: Ensure your terraform.tfstate is 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

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:

  1. Define a data source for aws_secretsmanager_secret_version to fetch the latest version of the secret. Give the data source a local name of db_creds.
  2. Use the input variable secret_arn to specify which secret to fetch.
  3. The secret's value is a JSON string located in the secret_string attribute of the data source.
  4. Create an output named database_password.
  5. The value for this output must be the db_password extracted from the parsed JSON secret.
  6. Crucially, you must ensure that the database_password output is marked as sensitive to 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 uses var.secret_arn for its secret_id.
  • An output "database_password" block.
  • The value of the output must correctly use the jsondecode() function to parse data.aws_secretsmanager_secret_version.db_creds.secret_string and access the db_password key.
  • The output block must contain the line sensitive = true.
hcl

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.