Crie e gerencie chaves KMS com o Terraform.
Visão geral
O KMS permite criar uma chave mestra padrão sem uma instância dedicado ou criar chaves dentro de uma instância do KMS (Key service overview).
Execute o código de exemplo com um único clique. Executar com um clique
Pré-requisitos
-
Usar diretamente sua conta Alibaba Cloud gera riscos de segurança caso as credenciais vazem. Crie um usuário do Resource Access Management (RAM) com um AccessKey. Para mais informações, consulte Create a RAM user e Create an AccessKey.
-
Anexe a política AliyunKMSFullAccess ao usuário RAM para conceder permissões completas no KMS. Manage RAM user permissions.
{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": [ "kms:*" ], "Resource": [ "*" ], "Condition": {} } ] } -
Prepare um ambiente Terraform usando um dos métodos a seguir:
Use o Terraform no Terraform Explorer: ambiente Terraform baseado em navegador, sem necessidade de instalação. Ideal para testes rápidos e gratuitos.
Create resources with Terraform: Terraform pré-instalado com credenciais configuradas automaticamente. Execute comandos diretamente no navegador.
Install and configure Terraform locally: recomendado para cenários com conectividade de rede limitada ou ambientes de desenvolvimento personalizados.
É necessário ter o Terraform 0.12.28 ou posterior. Execute terraform --version para verificar a versão.
Recursos utilizados
alicloud_kms_key: cria e gerencia chaves.
alicloud_kms_alias: cria e gerencia aliases.
Criar uma chave em uma instância do KMS
O exemplo a seguir cria uma chave em uma instância do KMS.
-
Crie um diretório com um arquivo de configuração
main.tf. O arquivo main.tf define os recursos a implantar. Certifique-se de já ter criado uma instância do KMS.variable "region" { default = "cn-shanghai" } provider "alicloud" { region = var.region } variable "instance_name" { default = "tf-kms-vpc-172-16" } variable "instance_type" { default = "ecs.n1.tiny" } # Use a data source to obtain information about available zones. Resources can be created only in the specified zones. data "alicloud_zones" "default" { available_disk_category = "cloud_efficiency" available_resource_creation = "VSwitch" available_instance_type = var.instance_type } # Create a VPC. resource "alicloud_vpc" "vpc" { vpc_name = var.instance_name cidr_block = "172.16.0.0/12" } # Create a vSwitch with the CIDR block 172.16.0.0/21. resource "alicloud_vswitch" "vsw" { vpc_id = alicloud_vpc.vpc.id cidr_block = "172.16.0.0/21" zone_id = data.alicloud_zones.default.zones.0.id vswitch_name = "terraform-example-1" } # Create another vSwitch with the CIDR block 172.16.128.0/17. resource "alicloud_vswitch" "vsw1" { vpc_id = alicloud_vpc.vpc.id cidr_block = "172.16.128.0/17" zone_id = data.alicloud_zones.default.zones.1.id vswitch_name = "terraform-example-2" } # Create a software key management instance and start it with network parameters. resource "alicloud_kms_instance" "default" { timeouts { delete = "20m" # Set a timeout period for deletion. } # A software key management instance. product_version = "3" vpc_id = alicloud_vpc.vpc.id # Specify the zones for the KMS instance using the obtained zone IDs. zone_ids = [ data.alicloud_zones.default.zones.0.id, data.alicloud_zones.default.zones.1.id ] # The vSwitch IDs. vswitch_ids = [ alicloud_vswitch.vsw.id,alicloud_vswitch.vsw1.id ] # The computing performance, number of keys, number of credentials, and number of access management operations. vpc_num = "1" key_num = "1000" secret_num = "100" spec = "1000" # Associate the KMS instance with other VPCs. This parameter is optional. # If the VPC and the VPC of the KMS instance belong to different Alibaba Cloud accounts, you must first share the vSwitch. #bind_vpcs { #vpc_id = "vpc-j6cy0l32yz9ttxfy6****" #vswitch_id = "vsw-j6cv7rd1nz8x13ram****" #region_id = "cn-shanghai" #vpc_owner_id = "119285303511****" #} #bind_vpcs { #vpc_id = "vpc-j6cy0l32yz9ttd7g3****" #vswitch_id = "vsw-3h4yrd1nz8x13ram****" #region_id = "cn-shanghai" #vpc_owner_id = "119285303511****" #} } # Save the CA certificate of the KMS instance to a local file. resource "local_file" "ca_certificate_chain_pem" { content = alicloud_kms_instance.default.ca_certificate_chain_pem filename = "ca.pem" }Crie uma chave na instância do KMS:
# The key specification is Aliyun_AES_256, and the key is used for encryption and decryption (ENCRYPT/DECRYPT). resource "alicloud_kms_key" "kms_software_key_encrypt_decrypt" { timeouts { delete = "20m" # Set a timeout period for deletion. } description = "default_key_encrypt_decrypt description" # The usage of the key. Default value: ENCRYPT/DECRYPT. Valid value: ENCRYPT/DECRYPT, which indicates that the key is used to encrypt or decrypt data. key_usage = "ENCRYPT/DECRYPT" # The specification of the key. Default value: Aliyun_AES_256. key_spec = "Aliyun_AES_256" # The source of the key material. Default value: Aliyun_KMS. Valid values: Aliyun_KMS and EXTERNAL. origin = "Aliyun_KMS" # The ID of the KMS instance. # If you add this parameter, a key is created in the KMS instance. Otherwise, a default master key is created. dkms_instance_id = alicloud_kms_instance.default.id # The number of days before the CMK is deleted. pending_window_in_days = 7 # The mapping of tags to assign to the resource. This is optional. #tags = { #"Environment" = "Production" #"Name" = "KMS-01" #"SupportTeam" = "PlatformEngineering" #"Contact" = "aliyun@test.com" #} } # The key alias is alias/kms_software_key_encrypt_decrypt, which must be unique within an Alibaba Cloud account. resource "alicloud_kms_alias" "kms_software_key_encrypt_decrypt_alias" { # The alias. alias_name = "alias/kms_software_key_encrypt_decrypt" # The key ID. key_id = alicloud_kms_key.kms_software_key_encrypt_decrypt.id } -
Inicialize o
Terraform:terraform initSaída esperada em caso de sucesso:
Initializing the backend... Initializing provider plugins... - Reusing previous version of hashicorp/alicloud from the dependency lock file - Using previously-installed hashicorp/alicloud v1.231.0 Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes that are required for your infrastructure. All Terraform commands should now work. If you ever set or change modules or backend configuration for Terraform, rerun this command to reinitialize your working directory. If you forget, other commands will detect it and remind you to do so if necessary. -
Crie um plano de execução e visualize as alterações.
terraform plan -
Crie a chave:
terraform applyInsira
yesquando solicitado e pressione Enter. Saída esperada em caso de sucesso:Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value: yes ... alicloud_kms_key.kms_software_key_encrypt_decrypt: Creating... alicloud_kms_key.kms_software_key_encrypt_decrypt: Creation complete after 0s [id=key-shh6715c21812y8i7z***] alicloud_kms_alias.kms_software_key_encrypt_decrypt_alias: Creating... alicloud_kms_alias.kms_software_key_encrypt_decrypt_alias: Creation complete after 0s [id=alias/kms_secret] ... Apply complete! Resources: 2 added, 0 changed, 0 destroyed. -
Verifique os resultados.
Executar o comando terraform show
Visualize os detalhes do recurso:
terraform show
Fazer login no console do Key Management Service
Acesse o console do Key Management Service para visualizar a chave.
Limpar recursos
Para liberar recursos desnecessários, execute o comando a seguir. Para mais informações sobre o terraform destroy, consulte Common Terraform commands.
terraform destroy
Exemplo completo
Execute o código de exemplo com um único clique. Executar com um clique