Course contentsShow
← Security
Lesson 3001 of 3,05256. Security Automation and ToolingFree lesson

Secrets Management in IaC

Preventing hardcoded credentials in IaC files using secret managers, encrypted variables, and runtime injection patterns.

Secrets Management in IaC

What You'll Learn

You'll learn how to prevent hardcoded credentials in Infrastructure as Code files by using secret managers, encrypted variables, and runtime injection patterns.

The Problem with Hardcoded Secrets

Infrastructure as Code (IaC) files—Terraform configs, Ansible playbooks, CloudFormation templates—are stored in version control alongside application code. The moment you hardcode an API key, database password, or certificate directly into these files, you've created a permanent security vulnerability. Even if you delete it later, the secret remains in Git history forever.

Think of IaC files like restaurant menus that get printed and distributed publicly. You wouldn't write the safe combination on the menu, even if only staff see it—the menu itself isn't secure storage.

Three Core Defense Patterns

1. Secret Managers

Store credentials in dedicated secret management services (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault). Your IaC references the secret's location, not its value:

# Reference, not the actual secret
database_password = data.vault_generic_secret.db.data["password"]

2. Encrypted Variables

Encrypt sensitive values before committing them using tools like sops, git-crypt, or ansible-vault. The encrypted blob is safe in version control; only authorized systems with decryption keys can read it at deployment time.

3. Runtime Injection

Pass secrets as environment variables or command-line parameters during execution, never embedding them in files. The IaC template declares that a secret is needed, but the actual value arrives from a secure runtime source.

Defense in Depth

Combine these approaches: use secret managers as the source of truth, inject secrets at runtime through CI/CD pipelines with proper access controls, and scan IaC files continuously with tools (like you learned in lesson 3000) to catch accidental hardcoding.

Key Takeaway: Never hardcode secrets in IaC files—use secret managers for storage, encryption for committed values when necessary, and runtime injection to keep credentials out of version control entirely.