All Products
Search
Document Center

Key Management Service:Create key by using Terraform

Last Updated:Feb 13, 2025

Terraform enables you to create and manage keys efficiently. This topic describes the steps to create a key.

Overview

KMS enables the creation of a default customer master key (CMK) without the need to purchase a KMS instance. Additionally, you can create keys within a KMS instance. For more information about keys, see the referenced document.

Note

The sample code provided can be executed with a single click. Run with one click

Prerequisites

  • Because an Alibaba Cloud account has full permissions over all associated resources, there are security risks if the account's credentials are compromised. It is recommended to use a RAM user and create an AccessKey for that user. For more information, see Create a RAM user and Create an AccessKey.

  • Assign the following permissions to the RAM user: AliyunKMSFullAccess, which grants full access to the Key Management Service. For more information, see Grant permissions to a RAM user.

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "kms:*"
          ],
          "Resource": [
            "*"
          ],
          "Condition": {}
        }
      ]
    }
  • Prepare the Terraform environment using one of the following methods:

    Utilize Terraform within Explorer: Alibaba Cloud offers an online Terraform environment, eliminating the need for installation. Once logged on, you can conveniently use and test Terraform online at no extra charge, ideal for scenarios where rapid and convenient Terraform usage and debugging are required.

    Cloud Shell: Alibaba Cloud Cloud Shell comes with Terraform pre-installed and identity credentials already configured. You can execute Terraform commands directly within Cloud Shell. This approach is ideal for situations where you need quick and cost-effective access to Terraform.

    Install and configure Terraform locally: Opt for this method in scenarios where network connectivity is limited or when a customized development environment is required.

Important

Ensure Terraform version 0.12.28 or later is installed. To verify the current version, execute the terraform --version command.

Resources

Create a key in a KMS instance

This example shows how to create a key within a KMS instance.

  1. Set up a working directory and create a configuration file named main.tf within it. The main.tf file is the primary Terraform file that defines the resources for deployment. Ensure a KMS instance is already created before proceeding:

    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 data sources to obtain available zone information. Resources can only be created in the specified zone.
    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 a CIDR block of 172.16.0.0/12
    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 a CIDR block of 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.0.id
      vswitch_name = "terraform-example-2"
    }
    # Create a KMS software key management instance and start it with network parameters
    resource "alicloud_kms_instance" "default" {
      timeouts {
        delete = "20m" # Set a timeout for deletion
      }
      # 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 = [
        data.alicloud_zones.default.zones.0.id,
        data.alicloud_zones.default.zones.1.id
      ]
      # Switch ID
      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"
      # Associate other VPCs with the KMS instance. Optional parameter.
      # If the VPC and the KMS instance's VPC belong to different Alibaba Cloud accounts, you need to share the switch first.
      #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 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"
    }

    To create a key in a KMS instance:

    # The key specification is Aliyun_AES_256, and the key purpose is encryption and decryption (ENCRYPT/DECRYPT).
    resource "alicloud_kms_key" "kms_software_key_encrypt_decrypt" {
      timeouts {
        delete = "20m" # Set a timeout for deletion
      }
      description = "default_key_encrypt_decrypt description"
      # The usage of the key. Default value: ENCRYPT/DECRYPT. Valid values: ENCRYPT/DECRYPT: 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, EXTERNAL.
      origin = "Aliyun_KMS"
      # The ID of the KMS instance.
      # If you add this parameter, it indicates that the key is created in a KMS instance. Otherwise, a default key (CMK) 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 tag mapping to assign to the resource. Optional.
      #tags = {
          #"Environment" = "Production"
          #"Name" = "KMS-01"
          #"SupportTeam" = "PlatformEngineering"
          #"Contact" = "aliyun@test.com"
        #}
    }
    # The key alias is alias/kms_software_key_encrypt_decrypt, which is unique within 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
    }
  2. To initialize the Terraform environment, execute the command below.

    terraform init

    If the output below is displayed, Terraform has been successfully initialized:

    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.
  3. Generate an execution plan to preview the changes:

    terraform plan
  4. Execute the following command to create a key:

    terraform apply

    During execution, type yes when prompted and press the Enter key. Wait for the command to finish. If the information below appears, the key has been created:

    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.
  5. Verify the result:

    Run the terraform show command

    Execute the command below to check the details of the resources created with Terraform:

    terraform show

    image

    Log on to the Key Management Service console

    Access the Key Management Service console to view the keys you've created.

Clean up resources

If you no longer require the resources previously created or managed by Terraform, you can execute the command below to remove them. For more details on terraform destroy, refer to Common commands.

terraform destroy

Complete example

Note

The sample code can be executed with a single click. Run with one click

Sample code

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 data sources to obtain available zone information. Resources can only be created in the specified zone.
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 a CIDR block of 172.16.0.0/12
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 a CIDR block of 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.0.id
  vswitch_name = "terraform-example-2"
}
# Create a KMS software key management instance and start it with network parameters
resource "alicloud_kms_instance" "default" {
  timeouts {
    delete = "20m" # Set a timeout for deletion
  }
  # 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 = [
    data.alicloud_zones.default.zones.0.id,
    data.alicloud_zones.default.zones.1.id
  ]
  # Switch ID
  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"
  # Associate other VPCs with the KMS instance. Optional parameter.
  # If the VPC and the KMS instance's VPC belong to different Alibaba Cloud accounts, you need to share the switch first.
  #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 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"
}

# The key specification is Aliyun_AES_256, and the key purpose is encryption and decryption (ENCRYPT/DECRYPT).
resource "alicloud_kms_key" "kms_software_key_encrypt_decrypt" {
  timeouts {
    delete = "20m" # Set a timeout for deletion
  }
  description = "default_key_encrypt_decrypt description"
  # The usage of the key. Default value: ENCRYPT/DECRYPT. Valid values: ENCRYPT/DECRYPT: 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.
  # If you add this parameter, it indicates that the key is created in a KMS instance. Otherwise, a default key (CMK) 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 tag mapping to assign to the resource. Optional.
  #tags = {
      #"Environment" = "Production"
      #"Name" = "KMS-01"
      #"SupportTeam" = "PlatformEngineering"
      #"Contact" = "aliyun@test.com"
    #}
}
# The key alias is alias/kms_software_key_encrypt_decrypt, which is unique within 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
}