Use o Terraform para criar e gerenciar segredos. Este tópico mostra como criar segredos.
Visão geral
O Key Management Service (KMS) protege os segredos ao criptografá-los com uma chave especificada. Portanto, crie uma chave antes de criar um segredo. Para mais informações sobre segredos, consulte Secrets management overview.
Execute o código de exemplo deste tópico com um único clique. Executar código
Pré-requisitos
-
O uso de uma conta Alibaba Cloud, que possui permissões totais sobre todos os recursos, apresenta alto risco de segurança caso as credenciais vazem. Como prática recomendada de segurança, use um usuário RAM e crie um par de AccessKey para esse usuário. Para mais informações, consulte Create a RAM user e Create an AccessKey.
-
Conceda ao usuário RAM a permissão AliyunKMSFullAccess para gerenciar o KMS e a permissão AliyunRAMFullAccess para gerenciar o Resource Access Management (RAM). Para mais informações, consulte Grant permissions to a RAM user.
{ "Version": "1", "Statement": [ { "Action": "kms:*", "Resource": "*", "Effect": "Allow" }, { "Action": "ram:CreateServiceLinkedRole", "Condition": { "StringEquals": { "ram:ServiceName": [ "secretsmanager-rds.kms.aliyuncs.com", "keystore.kms.aliyuncs.com" ] } }, "Resource": "*", "Effect": "Allow" } ] } -
Prepare um ambiente de execução do Terraform. Use o Terraform de uma das seguintes maneiras:
Use o Terraform no Terraform Explorer: a Alibaba Cloud fornece um ambiente online do Terraform disponível após o login. Não requer instalação. Este método é ideal para testar e depurar o Terraform de forma rápida e gratuita.
Use Terraform to quickly create resources: o Terraform vem pré-instalado no Alibaba Cloud Shell e as credenciais são configuradas automaticamente. Execute os comandos do Terraform diretamente no Cloud Shell. Este método é rápido, prático e de baixo custo para acessar e usar o Terraform.
Install and configure Terraform locally: este método é adequado caso sua conectividade de rede seja limitada ou você precise de um ambiente de desenvolvimento personalizado.
Certifique-se de que a versão do seu Terraform seja a v0.12.28 ou posterior. Para verificar a versão, execute o comando terraform --version.
Recursos utilizados
alicloud_kms_secret: cria e gerencia um segredo.
alicloud_vpc: provisiona uma Virtual Private Cloud (VPC).
alicloud_vswitch: cria um vSwitch para dividir uma VPC em uma ou mais sub-redes.
alicloud_kms_instance: adquire e ativa uma instância de gerenciamento de chaves de software do KMS.
alicloud_kms_key: cria e gerencia uma chave.
alicloud_kms_alias: cria e gerencia um alias.
Criar segredos usando o Terraform
Recomendamos definir sensitive = true para o argumento secret_data a fim de evitar que o valor confidencial do segredo seja exibido nos logs ou no console. Para mais informações, consulte Protect Sensitive Input Variables.
Este exemplo mostra como criar um segredo genérico.
-
Crie um diretório de trabalho e um arquivo de configuração chamado
main.tfnesse diretório.-
Adicione o seguinte conteúdo ao
main.tf. Certifique-se de já ter criado uma instância do KMS e uma chave.ImportanteA chave usada para criptografar o valor do segredo deve ser simétrica.
Crie uma instância do KMS:
variable "region" { default = "cn-heyuan" } provider "alicloud" { region = var.region } variable "instance_name" { default = "tf-kms-vpc-172-16" } # Create a VPC. resource "alicloud_vpc" "vpc" { vpc_name = var.instance_name cidr_block = "192.168.0.0/16" } # Create a vSwitch with the CIDR block 192.168.10.0/24. resource "alicloud_vswitch" "vsw" { vpc_id = alicloud_vpc.vpc.id cidr_block = "192.168.10.0/24" zone_id = "cn-heyuan-a" vswitch_name = "terraform-example-1" } # Create another vSwitch with the CIDR block 192.168.20.0/24. resource "alicloud_vswitch" "vsw1" { vpc_id = alicloud_vpc.vpc.id cidr_block = "192.168.20.0/24" zone_id = "cn-heyuan-b" vswitch_name = "terraform-example-2" } # Create a KMS software key management instance and start it with network parameters. resource "alicloud_kms_instance" "default" { # Software key management instance. product_version = "3" vpc_id = alicloud_vpc.vpc.id # The zones in which the KMS instance is deployed. Use the obtained zone IDs. zone_ids = [ "cn-heyuan-a", "cn-heyuan-b", ] # The vSwitch IDs. vswitch_ids = [ alicloud_vswitch.vsw.id,alicloud_vswitch.vsw1.id ] # The limits for computing performance, and the numbers of keys, secrets, and access management operations. vpc_num = "1" key_num = "1000" secret_num = "100" spec = "1000" # Optional. Associate other VPCs with the KMS instance. # If the VPC and 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" { description = "default_key_encrypt_decrypt description" # The usage of the key. Default value: ENCRYPT/DECRYPT. Valid value: ENCRYPT/DECRYPT, which specifies 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 ID of the KMS instance. dkms_instance_id = alicloud_kms_instance.default.id pending_window_in_days = 7 # Optional. The map of tags to assign to the resource. # tags = { # "Environment" = "Production" # "Name" = "KMS-01" # "SupportTeam" = "PlatformEngineering" # "Contact" = "ali***@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" { # Alias. alias_name = "alias/kms_software_key_encrypt_decrypt" # Key ID. key_id = alicloud_kms_key.kms_software_key_encrypt_decrypt.id } -
Adicione o seguinte conteúdo ao
main.tfpara criar os segredos.-
Segredo genérico
# Create a generic secret named kms_secret_general1 with the value secret_data_kms_secret_general1. resource "alicloud_kms_secret" "kms_secret_general" { # Name. secret_name = "kms_secret_general1" # Description. description = "secret_data_kms_secret_general" # Type. secret_type = "Generic" # Specifies whether to forcefully delete the secret. Default value: false. Valid values: true, false. force_delete_without_recovery = true # The ID of the KMS instance. dkms_instance_id = alicloud_kms_instance.default.id # The ID of the KMS key. encryption_key_id = alicloud_kms_key.kms_software_key_encrypt_decrypt.id # Version ID. version_id = "v1" # The type of the secret value. Default value: text. Valid values: text, binary. secret_data_type = "text" # Data. secret_data = "secret_data_kms_secret_general1" } -
Segredo RAM
# This example shows how to create a RAM secret. # Before you start, create a RAM user and an AccessKey pair for which you want to create a managed RAM secret. # This process consists of two steps. # Step 1: Grant KMS the permissions to manage the AccessKey pair of the RAM user. # 1.1 Create a custom policy named AliyunKMSManagedRAMCrendentialsRolePolicy. resource "alicloud_ram_policy" "AliyunKMSManagedRAMCrendentialsRolePolicy" { policy_name = "AliyunKMSManagedRAMCrendentialsRolePolicy" policy_document = <<EOF { "Version": "1", "Statement": [ { "Effect": "Allow", "Action": [ "ram:ListAccessKeys", "ram:CreateAccessKey", "ram:DeleteAccessKey", "ram:UpdateAccessKey" ], "Resource": "*" } ] } EOF description = "AliyunKMSManagedRAMCrendentialsRolePolicy" force = true } # 1.2 Create a RAM role named AliyunKMSManagedRAMCrendentialsRole. resource "alicloud_ram_role" "AliyunKMSManagedRAMCrendentialsRole" { name = "AliyunKMSManagedRAMCrendentialsRole" description = "AliyunKMSManagedRAMCrendentialsRole" document = <<EOF { "Statement": [ { "Action": "sts:AssumeRole", "Effect": "Allow", "Principal": { "Service": [ "kms.aliyuncs.com" ] } } ], "Version": "1" } EOF force = true } # 1.3 Attach the AliyunKMSManagedRAMCrendentialsRolePolicy policy to the AliyunKMSManagedRAMCrendentialsRole role. resource "alicloud_ram_role_policy_attachment" "attach" { policy_name = alicloud_ram_policy.AliyunKMSManagedRAMCrendentialsRolePolicy.policy_name policy_type = alicloud_ram_policy.AliyunKMSManagedRAMCrendentialsRolePolicy.type role_name = alicloud_ram_role.AliyunKMSManagedRAMCrendentialsRole.name } # Step 2: Create the RAM secret. resource "alicloud_kms_secret" "kms_secret_RAMCredentials" { # The name of the secret. secret_name = "my_secret" # The description. description = "secret_kms_secret_RAMCredentials" # The type of the secret. secret_type = "RAMCredentials" # The ID of the KMS instance. dkms_instance_id = alicloud_kms_instance.default.id # The ID of the key used to encrypt the secret value. encryption_key_id = alicloud_kms_key.kms_software_key_encrypt_decrypt.id # Specifies whether to forcefully delete the secret. Default value: false. Valid values: true, false. force_delete_without_recovery = true # Specifies whether to enable automatic rotation. Default value: false. Valid values: true, false. enable_automatic_rotation = true # The interval for automatic rotation. rotation_interval = "7d" # Extended configuration. Replace the value of UserName with your RAM user's name. extended_config = "{\"SecretSubType\":\"RamUserAccessKey\", \"UserName\":\"testuser\"}" # Version. version_id = "V1" # The type of the secret value. Default value: text. Valid values: text, binary. secret_data_type ="text" # The secret value. secret_data = "{\"AccessKeys\":[{\"AccessKeyId\":\"LTAI****************\",\"AccessKeySecret\":\"yourAccessKeySecret\"}]}" } -
Segredo RDS
Este exemplo mostra como criar um segredo RDS no modo de hospedagem de conta dupla.
variable "region" { default = "cn-hangzhou" } provider "alicloud" { region = var.region } variable "zone_id" { default = "cn-hangzhou-b" } variable "instance_type" { default = "pg.n2.2c.2m" } # Create a VPC. resource "alicloud_vpc" "main" { vpc_name = "alicloud" cidr_block = "172.16.0.0/16" } # Create a vSwitch. resource "alicloud_vswitch" "main" { vpc_id = alicloud_vpc.main.id cidr_block = "172.16.192.0/20" zone_id = var.zone_id depends_on = [alicloud_vpc.main] } # Create an ApsaraDB RDS for PostgreSQL instance. resource "alicloud_db_instance" "instance" { engine = "PostgreSQL" engine_version = "13.0" instance_type = var.instance_type instance_storage = "30" instance_charge_type = "Postpaid" vswitch_id = alicloud_vswitch.main.id } # Create an RDS secret. resource "alicloud_kms_secret" "kms_secret_RDS_MYSQL" { # The name of the secret. secret_name = "rds_secret/${alicloud_db_instance.id}" # The type of the secret. secret_type = "Rds" # The ID of the KMS instance. dkms_instance_id = alicloud_kms_instance.default.id # The ID of the key used to encrypt the secret value. encryption_key_id = alicloud_kms_key.kms_software_key_encrypt_decrypt.id # Specifies whether to enable automatic rotation. Default value: false. Valid values: true, false. enable_automatic_rotation = true # The interval for automatic rotation. rotation_interval = "7d" # Specifies whether to forcefully delete the secret. Default value: false. Valid values: true, false. force_delete_without_recovery = true # Configuration. extended_config = "{\"SecretSubType\":\"DoubleUsers\", \"DBInstanceId\":\"rm-7xv1450tq4pj4****\" ,\"CustomData\": {}}" # Version. version_id = "V1" # The type of the secret value. Default value: text. Valid values: text, binary. secret_data_type = "text" # The secret value. secret_data = "{\"Accounts\":[{\"AccountName\":\"rdsuser1\",\"AccountPassword\":\"Admin****\"},{\"AccountName\":\"rdsuser2\",\"AccountPassword\":\"Admin****\"}]}" } -
Segredo ECS
// Create an ECS secret. // Before you start, make sure that you have created an ECS instance with the ID i-bp14yu34xwbimp56****, the username root, and the password Admin****. // The secret type must be the uppercase value ECS. A value such as Ecs is rejected. Valid values: Generic, Rds, Redis, RAMCredentials, ECS, and PolarDB. // The secret name must start with acs/ecs/. resource "alicloud_kms_secret" "kms_secret_ECS" { secret_name = "acs/ecs/ecsSecretName" secret_data_type = "text" secret_data = "{\"UserName\":\"root\",\"Password\":\"Admin****\"}" secret_type = "ECS" version_id = alicloud_kms_key.kms_software_key_encrypt_decrypt.primary_key_version // The ID of the key used to encrypt the secret value. encryption_key_id = alicloud_kms_key.kms_software_key_encrypt_decrypt.id dkms_instance_id = var.soft_kms_instance enable_automatic_rotation = true rotation_interval = "7d" // In the extended configuration, the secret sub-type is either Password or SSHKey. The region ID and the ECS instance ID are also required. extended_config = "{\"SecretSubType\":\"Password\",\"RegionId\":\"eu-central-1\", \"InstanceId\":\"i-bp14yu34xwbimp56****\"}" force_delete_without_recovery = true }// Create an ECS secret of the SSHKey sub-type. // Before you start, make sure that you have created an ECS instance with the ID i-bp14yu34xwbimp56****, the username root, and an SSH key pair. resource "alicloud_kms_secret" "kms_secret_ECS_sshkey" { // The name of the secret must start with acs/ecs/. secret_name = "acs/ecs/ecsSecretSshKeyName" secret_data_type = "text" // For the SSHKey sub-type, the secret value must contain the user name, the public key, and the private key. secret_data = "{\"UserName\":\"root\",\"PublicKey\":\"ssh-rsa AAAAB3Nza****\",\"PrivateKey\":\"-----BEGIN RSA PRIVATE KEY-----****-----END RSA PRIVATE KEY-----\"}" // The type of the secret must be the uppercase value ECS. secret_type = "ECS" version_id = alicloud_kms_key.kms_software_key_encrypt_decrypt.primary_key_version // The ID of the key used to encrypt the secret value. encryption_key_id = alicloud_kms_key.kms_software_key_encrypt_decrypt.id dkms_instance_id = var.soft_kms_instance // Set the secret sub-type to SSHKey, and specify the region and the instance ID of the ECS instance. extended_config = "{\"SecretSubType\":\"SSHKey\",\"RegionId\":\"cn-hangzhou\", \"InstanceId\":\"i-bp14yu34xwbimp56****\"}" force_delete_without_recovery = true }
-
-
-
Execute o seguinte comando para inicializar o ambiente de execução do
Terraform.terraform initTerraform has created a lock file .terraform.lock.hcl to record the provider selections it made above. Include this file in your version control repository so that Terraform can guarantee to make the same selections by default when you run "terraform init" in the future. 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 -
Execute o seguinte comando para criar o segredo genérico:
terraform applyNo prompt, insira
yese pressione Enter. Aguarde a conclusão do comando. Uma saída semelhante à seguinte indica que o segredo genérico foi criado.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: Creation complete after 0s [id=key-shh6715c21812y8i7z***] alicloud_kms_alias.kms_software_key_encrypt_decrypt_alias: Creating... alicloud_kms_secret.kms_secret_general: Creating... alicloud_kms_alias.kms_software_key_encrypt_decrypt_alias: Creation complete after 0s [id=alias/kms_secret] alicloud_kms_secret.kms_secret_general: Creation complete after 1s [id=kms_secret_general1] ... Apply complete! Resources: 2 added, 0 changed, 0 destroyed. -
Verifique os resultados
Terraform show
Execute o seguinte comando para visualizar os detalhes dos recursos criados com o Terraform:
terraform show"Name" = "KMS-001" "SupportTeam" = "PlatformEngineering" } } # alicloud_kms_secret.kms_secret_general: resource "alicloud_kms_secret" "kms_secret_general" { arn = "acs:kms:xxx:xxx/kms_secret_general1" create_time = "2024-10-21T02:53:13Z" description = "secret_data_kms_secret_general" dkms_instance_id = "kst-xxx" enable_automatic_rotation = false encryption_key_id = "key-xxx" force_delete_without_recovery = false id = "kms_secret_general1" policy = jsonencode( { Statement = [ { Action = [ "kms:*", ] Effect = "Allow" Principal = { RAM = [ "acs:ram::xxx:*", ] } Resource = [ "*", ] Sid = "kms default secret policy" }, ] Version = "1" } ) recovery_window_in_days = 30 secret_data = (sensitive value) secret_data_type = "text" secret_name = "kms_secret_general1" secret_type = "Generic" tags = {} version_id = "v1" version_stages = [ "ACSCurrent", ] }Acesse o console do KMS
Acesse o console do Key Management Service para visualizar o segredo criado.
Limpar recursos
Quando você não precisar mais dos recursos gerenciados pelo Terraform, execute o seguinte comando para liberá-los. Para mais informações sobre o comando terraform destroy, consulte common commands.
terraform destroy
Exemplo completo
Execute o código de exemplo deste tópico com um único clique. Executar código