Skip to the page
Tecyfy

AWS interview question · hard

What are the best practices for managing sensitive information, such as AWS credentials, in Terraform without hardcoding them?

The short answerNever write credentials in Terraform files.

The full answer

Never write credentials in Terraform files. Let the AWS provider pick up short-lived credentials from the environment (SSO, an assumed role, or OIDC in CI), keep application secrets in a secret store and pass them in as ephemeral or write-only values, and protect the state file, which can still contain secrets.

1. AWS credentials: short-lived, from outside the code

  • On a laptop: aws sso login with IAM Identity Center, and AWS_PROFILE naming the profile. The provider reads the shared config automatically.
  • In CI: OpenID Connect. GitHub Actions, GitLab and others exchange a token for temporary credentials of an IAM role, so no access keys are stored anywhere.
  • On AWS compute (CodeBuild, EC2, ECS): the attached role's credentials.
  • Across accounts: an assume_role block in the provider.
  • Environment variables (AWS_ACCESS_KEY_ID and friends) work, but long-lived keys are the last resort.

2. Application secrets (database passwords, API keys)

  • Store them in AWS Secrets Manager or SSM Parameter Store (SecureString), or HashiCorp Vault.
  • Better still, let the service own the secret: for RDS, manage_master_user_password = true makes RDS generate the password and keep it in Secrets Manager, so Terraform never sees it.
  • Mark variables that carry secrets sensitive = true, so Terraform hides them in plan and output. This does not keep them out of state.
  • Ephemeral values (Terraform 1.10 and later): ephemeral = true on a variable, or ephemeral resources that read a secret, are never written to plan or state.
  • Write-only arguments (Terraform 1.11 and later), such as password_wo on supported resources, accept ephemeral values and are never stored.
variable "db_password" {
  type      = string
  sensitive = true
  ephemeral = true
}

3. Protect state and plans

  • Use a remote backend (an S3 bucket with encryption, versioning, locking and tightly limited access, or HCP Terraform), never local state committed to Git.
  • Saved plan files can contain sensitive values too; treat them like secrets.

4. Keep secrets out of Git

  • .gitignore for *.tfvars files that hold secret values, .terraform/ and state files.
  • Secret scanning (for example GitHub push protection or gitleaks) in pre-commit hooks and CI.
  • Never pass secrets with -var on the command line, where they end up in shell history.

5. Least privilege for Terraform itself

  • Separate roles per environment, and a read-only role for plan on pull requests.

A good answer separates the two problems: how Terraform authenticates to AWS (temporary credentials, no keys) and how it handles secrets for resources (a secret store, ephemeral values, protected state).

Last updated 16 October 2026