Encrypting secrets in Hashicorp Terraform
To encrypt data:
-
In the configuration file, describe the parameters of the
yandex_kms_secret_ciphertextresource and specify the KMS key in thekey_idfield:resource "yandex_kms_secret_ciphertext" "password" { key_id = "<key_ID>" aad_context = "additional authenticated data" plaintext = "strong password" }Where:
key_id: KMS key ID.aad_context: AAD context.plaintext: String to encrypt.
Warning
With
yandex_kms_secret_ciphertext, you can hide secrets when deploying an infrastructure, but generally speaking it is unsafe to specifyplaintextandaad_contextin the configuration file in plain text. Secrets can be read from configuration files or execution logs and can end up in the Terraform state.For more information about resource properties in Terraform, see this provider guide.
-
Validate your configuration using this command:
terraform validateIf the configuration is valid, you will get this message:
Success! The configuration is valid. -
Run this command:
terraform planYou will see a list of resources and their properties. No changes will be made at this step. Terraform will show any errors in the configuration.
-
Apply the configuration changes:
terraform apply -
Type
yesand press Enter to confirm the changes.After this, you can access the ciphertext through the
ciphertextvariable, and the encrypted data, throughplaintext.For verification, you can add the following code with the
decrypted_passoutput variable to the configuration file.Alert
This is not safe and can only be used for testing.
output "decrypted_pass" { sensitive = true value = yandex_kms_secret_ciphertext.password.plaintext }After updating the configuration, you can check the encrypted data using the command:
terraform output decrypted_passResult:
"strong password"
Recommendations for safely storing secret data
- Do not explicitly specify the secret values in the configuration file. Read them from a storage with restricted access (e.g., a secret storage).
- Consider storing the Terraform state remotely
.