Managing KMS keys with Hashicorp Terraform
The Terraform provider
Adding keys
To create a key:
-
Describe the parameters of the
yandex_kms_symmetric_key
resource in the configuration file:resource "yandex_kms_symmetric_key" "key-a" { name = "<key_name>" description = "<key_description>" default_algorithm = "AES_128" rotation_period = "8760h" lifecycle { prevent_destroy = true } }
Where:
-
name
: Key name. The name format is as follows:- The name must be from 3 to 63 characters long.
- It may contain lowercase Latin letters, numbers, and hyphens.
- The first character must be a letter and the last character cannot be a hyphen.
-
description
: Key description. -
default_algorithm
: Encryption algorithm. The possible values areAES-128
,AES-192
, orAES-256
. -
rotation_period
: Rotation period (how often to change key versions). To create a key without automatic rotation, do not specify therotation_period
parameter.
Warning
Deleting a KMS key destroys all data encrypted with that key: the data becomes unrecoverable after the key is deleted. The
lifecycle
block is necessary to prevent users from destroying keys (e.g., with theterraform destroy
command).For more information about resource parameters in Terraform, see the provider documentation
. -
-
Check the configuration using this command:
terraform validate
If the configuration is correct, you will get this message:
Success! The configuration is valid.
-
Run this command:
terraform plan
The 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
yes
into the terminal and press Enter.All the resources you need will then be created in the specified folder. You can check the new resources and their configuration using the management console
or these CLI commands:yc kms symmetric-key list
Managing key access
To manage access to keys in Terraform, assign the necessary roles for the folder that contains the key.
For example, assign the kms.keys.encrypterDecrypter
role for the service account, which grants the permission to encrypt and decrypt data with keys from a specific folder:
resource "yandex_resourcemanager_folder_iam_member" "admin" {
folder_id = "<folder_ID>"
role = "kms.keys.encrypterDecrypter"
member = "serviceAccount:<service_account_ID>"
}