Prompt
Need to keep secrets out of Terraform state
Latest observation
Yes — you generally want to avoid putting secrets into Terraform state, because state is often stored remotely, shared with teammates/automation, and can persist longer than you expect.
Best options
1) Don’t manage the secret value with Terraform
Use Terraform to create the resource, but inject the secret outside Terraform:
- CI/CD secret store
- Vault
- AWS Secrets Manager / SSM Parameter Store
- Azure Key Vault
- GCP Secret Manager
Then have your app or runtime fetch the secret directly from that store.
2) Pass secret values as sensitive variables
If you must pass a secret into Terraform:
- mark the variable as
sensitive = true - avoid outputting it
- avoid using it in resource arguments unless unavoidable
Example:
variable "db_password" {
type = string
sensitive = true
}
This hides it from CLI output, but it can still end up in state if used in a resource.
3) Use resources that reference secret IDs, not secret values
Prefer patterns like:
- store secret in a secret manager
- pass only the secret ARN/name/ID into Terraform
- configure the consuming service to read it at runtime
Example:
resource "aws_secretsmanager_secret" "db" {
name = "db-password"
}
resource "aws_secretsmanager_secret_version" "db" {
secret_id = aws_secretsmanager_secret.db.id
secret_string = var.db_password
}
This still stores the value in Terraform state, so it’s only acceptable if you understand the tradeoff.
If you must use Terraform with secrets
Minimize exposure:
- use an encrypted remote backend
- restrict state access tightly
- enable state encryption at rest and in transit
- use short-lived credentials
- rotate secrets regularly
- do not commit state locally or to git
Important limitation
Terraform cannot fully prevent secrets from entering state if the secret value is part of the resource configuration. sensitive only hides it in UI/plan output; it does not guarantee it stays out of state.
Practical rule
If the value is a true secret, try to:
- store it outside Terraform
- have Terraform manage only references to it
If you want, I can show you the safest pattern for a specific provider like AWS, Azure, GCP, or Kubernetes.