Terraformを使用して、シークレットを作成および管理できます。 このトピックでは、作成方法について説明します。
前提条件
Resource Access Management (RAM) ユーザーとそのAccessKeyペアが作成されている必要があります。 手順については、「RAMユーザーの作成」および「AccessKeyペアの作成」をご参照ください。
セキュリティを確保するため、Alibaba CloudアカウントではなくRAMユーザーを使用してリソースを管理することを推奨します。 Alibaba Cloudアカウントにはすべてのリソースへのフルアクセスがあり、侵害された場合、重大なセキュリティリスクが発生します。
RAMユーザーに次の権限を付与していること。
AliyunKMSFullAccess: キー管理サービス (KMS) を管理します。AliyunRAMFullAccess: RAMアクセス制御の権限を管理します。手順については、「RAMユーザーへの権限の付与」をご参照ください。
あなたはTerraform環境を準備しました。
Terraform Explorerの使用: Alibaba Cloudが提供するツールを使用すると、インストールなしでTerraform構成ファイルをオンラインでデバッグできます。 オープンソースのTerraformをベースにして、ゼロコストで迅速かつ便利なデバッグを可能にします。 ログイン後、すぐに開始できます。
Cloud ShellでのTerraformの使用: TerraformコンポーネントはAlibaba Cloud Cloud Shellにプリインストールされており、ID認証情報はすでに設定されています。 TerraformコマンドをCloud Shellで直接実行すると、すばやく低コストでアクセスできます。
Terraformのインストールと設定: ネットワーク接続が不十分な場合や、カスタム開発環境が必要な場合に適しています。
Terraform V0.12.28以降を使用していることを確認します。 現在のバージョンを確認するには、terraform -- versionコマンドを実行します。
使用されたリソース
alicloud_kms_secret: シークレットを作成および管理します。
alicloud_vpc: VPC (Virtual Private Cloud) を作成します。
alicloud_vswitch: VPCを1つ以上のサブネットにセグメント化するvSwitchを作成します。
alicloud_kms_instance: KMSインスタンスを購入してアクティブ化します。
alicloud_kms_key: カスタマーマスターキー (CMK) を作成および管理します。
alicloud_kms_alias: CMKのエイリアスを作成および管理します。
手順
ログやKMSコンソールで機密秘密の値が印刷されないように、secret_dataでsensitive = trueを指定することを推奨します。 詳細については、「機密入力変数の保護」をご参照ください。
作業ディレクトリと
main.tfという名前のファイルをディレクトリに作成します。次の内容を
main.tfファイルに追加してKMSインスタンスを作成し、秘密の値を暗号化するために使用される対称キーを作成します。KMSはキーを使用してシークレットを暗号化および保護します。 シークレットを作成するには、まずキーを作成する必要があります。 シークレットの詳細については、「シークレット」をご参照ください。
KMSインスタンスを作成します。
variable "region" { default = "Singapore" } 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 CIDR block of 192.168.10.0/24. resource "alicloud_vswitch" "vsw" { vpc_id = alicloud_vpc.vpc.id cidr_block = "192.168.10.0/24" zone_id = "ap-southeast-1a" vswitch_name = "terraform-example-1" } # Create another VSwitch with CIDR block of 192.168.20.0/24. resource "alicloud_vswitch" "vsw1" { vpc_id = alicloud_vpc.vpc.id cidr_block = "192.168.20.0/24" zone_id = "ap-southeast-1b" vswitch_name = "terraform-example-2" } # Create a KMS software key management instance and launch it using network parameters. resource "alicloud_kms_instance" "default" { # Software key management instance. product_version = "3" vpc_id = alicloud_vpc.vpc.id # Specify zones for the KMS instance, using the previously obtained zone IDs. zone_ids = [ "ap-southeast-1a", "ap-southeast-1b", ] # VSwitch IDs. vswitch_ids = [ alicloud_vswitch.vsw.id,alicloud_vswitch.vsw1.id ] # Specify Compute performance, number of keys, number of secrets, number of access management. 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's VPC belong to different Alibaba Cloud accounts, you need to share the VSwitch first. #bind_vpcs { #vpc_id = "vpc-j6cy0l32yz9ttxfy6****" #vswitch_id = "vsw-j6cv7rd1nz8x13ram****" #region_id = "Malaysia (Kuala Lumpur)" #vpc_owner_id = "119285303511****" #} #bind_vpcs { #vpc_id = "vpc-j6cy0l32yz9ttd7g3****" #vswitch_id = "vsw-3h4yrd1nz8x13ram****" #region_id = "Malaysia (Kuala Lumpur)" #vpc_owner_id = "119285303511****" #} } # Save the KMS instance CA certificate to a local file. resource "local_file" "ca_certificate_chain_pem" { content = alicloud_kms_instance.default.ca_certificate_chain_pem filename = "ca.pem" }KMSインスタンス内に対称キーを作成します。
# The key specification is Aliyun_AES_256, and the key usage is encryption and decryption (ENCRYPT/DECRYPT) resource "alicloud_kms_key" "kms_software_key_encrypt_decrypt" { description = "default_key_encrypt_decrypt description" # The key usage. Default value: ENCRYPT/DECRYPT. Valid values: ENCRYPT/DECRYPT: Encrypt or decrypt data. key_usage = "ENCRYPT/DECRYPT" # The key specification. 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 tag mapping 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 is unique within 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 }
次のコンテンツを
main.tfに追加してシークレットを作成します。ジェネリックシークレットを作成する:
# Create a generic secret. The secret name is kms_secret_general1, and the secret value is 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" # Specify whether to delete immediately. 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 number. version_id = "v1" # The type of value. Default value: text. Valid values: text, binary. secret_data_type = "text" # Data. secret_data = "secret_data_kms_secret_general1" }RAMシークレットを作成する:
# An example of creating a RAM secret. # The prerequisite is that you have created a RAM user and AccessKey that need to host the RAM secret. # Two steps are required. # Step 1: Grant the KMS permission to manage the RAM user's AccessKey. # 1.1 Create a custom permission policy 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 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 Grant the RAM role AliyunKMSManagedRAMCrendentialsRole the AliyunKMSManagedRAMCrendentialsRolePolicy. 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 RAM credentials. resource "alicloud_kms_secret" "kms_secret_RAMCredentials" { # Secret name. secret_name = "my_secret" # Description. description = "secret_kms_secret_RAMCredentials" # Type of the secret. secret_type = "RAMCredentials" # KMS instance ID. 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 # Specify whether to delete the secret immediately. Default value: false. Valid values: true, false. force_delete_without_recovery = true # Specify whether to enable automatic rotation. Default value: false. Valid values: true, false. enable_automatic_rotation = true # Interval for automatic rotation. rotation_interval = "7d" # Extended configuration. Replace with your UserName. extended_config = "{\"SecretSubType\":\"RamUserAccessKey\", \"UserName\":\"testuser\"}" # Version. version_id = "V1" # Type of the secret value. Default value: text. Valid values: text, binary. secret_data_type ="text" # Data. secret_data = "{\"AccessKeys\":[{\"AccessKeyId\":\"LTAI****************\",\"AccessKeySecret\":\"yourAccessKeySecret\"}]}" }デュアルアカウント管理モードでApsaraDB RDSシークレットを作成します。
variable "region" { default = "Singapore" } provider "alicloud" { region = var.region } variable "zone_id" { default = "ap-southeast-1a" } 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 switch. 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 RDS 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" { # Secret name. secret_name = "rds_secret/${alicloud_db_instance.id}" # Type. secret_type = "Rds" # KMS instance ID. 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 # Specify whether to enable automatic rotation. Default value: false. Valid values: true, false. enable_automatic_rotation = true # Interval for automatic rotation. rotation_interval = "7d" # Specify whether to delete immediately. 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" # Type of secret value. Default value: text. Valid values: text, binary. secret_data_type = "text" # Data. secret_data = "{\"Accounts\":[{\"AccountName\":\"rdsuser1\",\"AccountPassword\":\"Admin****\"},{\"AccountName\":\"rdsuser2\",\"AccountPassword\":\"Admin****\"}]}" }
terraform initコマンドを実行してTerraformを初期化します。このコマンドは、必要なプロバイダをダウンロードし、Terraformバックエンドを初期化します。 次のような出力が表示されます。
Terraform has created a lock file .terraform.lock.hcl to record the provider selections...Include this file in your version control repository... Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes...terraform planコマンドを実行して、変更の計画とプレビューを行います。このコマンドは、Terraformが作成、変更、または破棄するリソースの詳細を示す実行計画を作成します。 出力が期待どおりになるように注意深く確認してください。
terraform applyコマンドを実行して、設定を適用します。Terraformは変更の確認を促します。
はいと入力し、Enterキーを押して続行します。 リソース作成の進行状況を示す出力が表示されます。 成功した完了は次のようになります。alicloud_kms_key.kms_software_key_encrypt_decrypt: Creation complete after 0s ... ... Apply complete! Resources: 2 added, 0 changed, 0 destroyed.結果を確認します。
次の2つの方法でシークレットの作成を確認できます。
terraform showを使用します。このコマンドは、作成されたリソースの属性を含む、インフラストラクチャの現在の状態を表示します。
KMSコンソールを使用します。
KMSコンソールにログインし、上部のナビゲーションバーで対象のリージョンを選択します。
左側のナビゲーションウィンドウで、 を選択して、作成した秘密を確認します。
クリーンアップリソース
Terraformによって以前に作成または管理されたリソースが不要になった場合は、terraform destroyコマンドを実行してそれらを削除できます。 詳細については、「一般的なコマンド」をご参照ください。
サンプルコード
このトピックのサンプルコードは、ワンクリック実行をサポートしています。 コードを直接実行できます。
variable "region" {
default = "Singapore"
}
provider "alicloud" {
region = var.region
}
variable "instance_name" {
default = "tf-kms-vpc-172-16"
}
# Create a VPCresource "alicloud_vpc" "vpc" {
vpc_name = var.instance_name
cidr_block = "192.168.0.0/16"
}
# Create a Vswitch with a CIDR block of 192.168.10.0/24resource "alicloud_vswitch" "vsw" {
vpc_id = alicloud_vpc.vpc.id
cidr_block = "192.168.10.0/24"
zone_id = "ap-southeast-1a"
vswitch_name = "terraform-example-1"
}
# Create another Vswitch with a CIDR block of 192.168.20.0/24resource "alicloud_vswitch" "vsw1" {
vpc_id = alicloud_vpc.vpc.id
cidr_block = "192.168.20.0/24"
zone_id = "ap-southeast-1b"
vswitch_name = "terraform-example-2"
}
# Create a KMS software key management instance and start it with network parametersresource "alicloud_kms_instance" "default" {
# Software key management instance
product_version = "3"
vpc_id = alicloud_vpc.vpc.id
# Specify the zone where the KMS instance is located. Use the zone ID obtained earlier.
zone_ids = [
"ap-southeast-1a",
"ap-southeast-1b",
]
# Switch IDs
vswitch_ids = [
alicloud_vswitch.vsw.id,alicloud_vswitch.vsw1.id
]
# Compute performance, number of keys, number of credentials, number of access management
vpc_num = "1"
key_num = "1000"
secret_num = "100"
spec = "1000"
}
# Save the KMS instance CA certificate to a local fileresource "local_file" "ca_certificate_chain_pem" {
content = alicloud_kms_instance.default.ca_certificate_chain_pem
filename = "ca.pem"
}
# The key specification is Aliyun_AES_256, and the key usage is encryption and decryption (ENCRYPT/DECRYPT)resource "alicloud_kms_key" "kms_software_key_encrypt_decrypt" {
timeouts {
delete = "30m" # Set a timeout for deletion
}
description = "default_key_encrypt_decrypt description"# The key usage. Default value: ENCRYPT/DECRYPT. Valid values: ENCRYPT/DECRYPT: Encrypt or decrypt data.
key_usage = "ENCRYPT/DECRYPT"# The key specification. 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
}
# The key alias is alias/kms_software_key_encrypt_decrypt, which is unique across the entire 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
}
# Create a generic credential. The credential name is kms_secret_general1, and the credential value is secret_data_kms_secret_general1resource "alicloud_kms_secret" "kms_secret_general" {
# Name
secret_name = "kms_secret_general1"# Description
description = "secret_data_kms_secret_general"# Type
secret_type = "Generic"# Specify whether to delete immediately. 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 number
version_id = "v1"# The type of value. Default value: text. Valid values: text, binary.
secret_data_type = "text"# Data
secret_data = "secret_data_kms_secret_general1"
}