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 be encrypted.
Warning
yandex_kms_secret_ciphertextenables you to hide secrets when deploying an infrastructure. However, in general, it is not safe to openly specify theplaintextandaad_contextin the configuration file. Secrets can be read from configuration files or execution logs and can end up in the Terraform state.For more information about resource parameters in Terraform, see the provider documentation.
-
Check the configuration using this command:
terraform validateIf the configuration is correct, you will get this message:
Success! The configuration is valid. -
Run this command:
terraform planThe terminal will display a list of resources with parameters. No changes will be made at this step. If the configuration contains any errors, Terraform will point them out.
-
Apply the configuration changes:
terraform apply -
Confirm the changes: type
yesinto the terminal and press Enter.The ciphertext can then be accessed via the
ciphertextvariable, and the encrypted data via theplaintextvariable.To check, 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
.