Category: Software, Database, Data, Terraform, Hashicorp, encryption, yaml

One of the most common questions we get about using Terraform to manage infrastructure as code is how to handle secrets such as passwords, API keys, and other sensitive data? For example, do NOT hard-code your database credentials directly in your Terraform code and check it into version control: Storing secrets in plain text in version control is a BAD IDEA.

First, you’ll need to store your secrets by using the pass insert command: You can read a secret out to stdout by running pass : You can use this functionality in a subshell to set your secrets as environment variables and then call terraform apply: The second technique relies on encrypting the secrets, storing the cipher text in a file, and checking that file into version control.

Now, in your terragrunt.hcl config, you can use the sops_decrypt_file function built into Terragrunt to decrypt that file and yamldecode to parse it as YAML: Next, you can pass username and password as inputs to your Terraform code: Your Terraform code, in turn, can read these inputs via variables: And pass those variables through to aws_db_instance: The third technique relies on storing your secrets in a dedicated secret store: that is, a database that is designed specifically for securely storing sensitive data and tightly controlling access to it.

Now, in your Terraform code, you can use the aws_secretsmanager_secret_version data source to read this secret (for HashiCorp Vault, AWS SSM Param Store, or GCP Secret Store, you’d instead use the vault_generic_secret, aws_ssm_parameter, or google_secret_manager_secret_version data source): If you stored the secret data as JSON, you can use jsondecode to parse it: And now you can use those secrets in the rest of your Terraform code: Here are your key takeaways from this blog post: Your entire infrastructure.

Related Articles