All Products
Search
Document Center

Key Management Service:Create a key with Terraform

Last Updated:Feb 24, 2025

You can use Terraform to create and manage keys. This topic describes how to create a key.

Overview

Key Management Service (KMS) allows you to create a default key of the customer master key (CMK) type. You do not need to purchase a KMS instance. You can also create keys in a KMS instance. For more information about keys, see Overview of key management.

Note

You can run the sample code in this topic with a few clicks. For more information, visit Terraform Explorer.

Limits

The Terraform version must be 0.14.0 or later. We recommend that you use the latest version. You can go to the Terraform official website to download the latest version.

Prerequisites

  • An Alibaba Cloud account has full permissions on all resources that belong to this account. If the credentials of an Alibaba Cloud account are leaked, security risks may arise. We recommend that you use a Resource Access Management (RAM) user and create an AccessKey pair for the RAM user. For more information, see Create a RAM user and Create an AccessKey pair.

  • The following code provides an example on how to grant permissions to RAM users. Make sure that the AliyunKMSFullAccess policy is attached to the RAM user. For more information, see Grant permissions to a RAM user.

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "kms:*"
          ],
          "Resource": [
            "*"
          ],
          "Condition": {}
        }
      ]
    }
  • The runtime environment for Terraform is prepared by using one of the following methods:

    Use Terraform in Terraform Explorer: Alibaba Cloud provides an online runtime environment for Terraform. You can log on to the Terraform Explorer environment to use Terraform without the need to install Terraform. This method is suitable for scenarios in which you want to use and debug Terraform in a fast and convenient manner at no additional costs.

    Use Terraform in Cloud Shell: Terraform is preinstalled in Cloud Shell, and identity credentials are configured. You can run Terraform commands in Cloud Shell. This method is suitable for scenarios in which you want to use and debug Terraform in a fast and convenient manner at low costs.

    Install and configure Terraform on your on-premises machine: This method is suitable for scenarios in which network connections are unstable or a custom development environment is required.

Important

You must install Terraform 0.12.28 or later. You can run the terraform --version command to query the Terraform version.

Required resources

Create a key in a KMS instance

In the following example, a key is created in a KMS instance.

  1. Create a working directory and a configuration file named main.tf in the working directory. main.tf is the main file of Terraform and defines the resources that you want to deploy. Make sure that a KMS instance is created in advance.

    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 information about available zones. You can create resources only in specified zones.
    data "alicloud_zones" "default" {
      available_disk_category     = "cloud_efficiency"
      available_resource_creation = "VSwitch"
      available_instance_type     = var.instance_type
    }
    # Create a virtual private cloud (VPC).
    resource "alicloud_vpc" "vpc" {
      vpc_name   = var.instance_name
      cidr_block = "172.16.0.0/12"
    }
    # Create a vSwitch whose CIDR block is 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 whose CIDR block is 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 an instance of the software key management type and configure network parameters to enable the instance.
    resource "alicloud_kms_instance" "default" {
      timeouts {
        delete = "20m" # Specify a deletion timeout period.
      }
      # The instance of the software key management type.
      product_version = "3"
      vpc_id          = alicloud_vpc.vpc.id
      # Specify zones for the KMS instance by 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 secrets, and access management quota.
      vpc_num    = "1"
      key_num    = "1000"
      secret_num = "100"
      spec       = "1000"
      # Associate a different VPC with the instance. This parameter is optional.
      # If the two VPCs belong to different Alibaba Cloud accounts, you must first share the vSwitch in the second VPC with the first VPC.
      #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 certificate authority (CA) certificate of the instance to a local file.
     resource "local_file" "ca_certificate_chain_pem" {
     content  = alicloud_kms_instance.default.ca_certificate_chain_pem
     filename = "ca.pem"
    }

    Create a key in the KMS instance:

    # The specification of the key is Aliyun_AES_256, and the usage of the key is ENCRYPT/DECRYPT.
    resource "alicloud_kms_key" "kms_software_key_encrypt_decrypt" {
      timeouts {
        delete = "20m" # Specify a deletion timeout period.
      }
      description = "default_key_encrypt_decrypt description"
      # The usage of the key. Default value: ENCRYPT/DECRYPT.
      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 specify this parameter, the key is created in the KMS instance. If you leave the parameter empty, the default key of the CMK type 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 tags that are added to the key for resource mapping. This parameter is optional.
      #tags = {
          #"Environment" = "Production"
          #"Name" = "KMS-01"
          #"SupportTeam" = "PlatformEngineering"
          #"Contact" = "aliyun@test.com"
        #}
    }
    # The alias of the key is alias/kms_software_key_encrypt_decrypt, which is unique within the Alibaba Cloud account.
    resource "alicloud_kms_alias" "kms_software_key_encrypt_decrypt_alias" {
      # The alias of the key.
      alias_name = "alias/kms_software_key_encrypt_decrypt"
      # The ID of the key.
      key_id = alicloud_kms_key.kms_software_key_encrypt_decrypt.id
    }
  2. Run the following command to initialize the runtime environment for Terraform.

    terraform init

    If the following information is returned, Terraform is 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. Create an execution plan and preview the changes.

    terraform plan
  4. Run the following command to create a key.

    terraform apply

    During the execution, enter yes as prompted and press the Enter key. Wait until the command is executed. If the following information is returned, the key is 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

    You can run the following command to query the resources that are created by using Terraform:

    terraform show

    image

    Log on to the KMS console

    Log on to the KMS console to view the created key.

Release resources

If you no longer require the preceding resources that are created or managed by using Terraform, run the following command to release the resources. For more information about terraform destroy, see Common commands.

terraform destroy

Complete sample code

Note

You can run the sample code with a few clicks. For more information, visit Terraform Explorer.

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 information about available zones. You can create resources only in 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 whose CIDR block is 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 whose CIDR block is 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 an instance of the software key management type and configure network parameters to enable the instance.
resource "alicloud_kms_instance" "default" {
  timeouts {
    delete = "20m" # Specify a deletion timeout period.
  }
  # The instance of the software key management type.
  product_version = "3"
  vpc_id          = alicloud_vpc.vpc.id
  # Specify zones for the KMS instance by 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 secrets, and access management quota.
  vpc_num    = "1"
  key_num    = "1000"
  secret_num = "100"
  spec       = "1000"
  # Associate a different VPC with the instance. This parameter is optional.
  # If the two VPCs belong to different Alibaba Cloud accounts, you must first share the vSwitch in the second VPC with the first VPC.
  #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 instance to a local file.
 resource "local_file" "ca_certificate_chain_pem" {
 content  = alicloud_kms_instance.default.ca_certificate_chain_pem
 filename = "ca.pem"
}

# The specification of the key is Aliyun_AES_256, and the usage of the key is ENCRYPT/DECRYPT.
resource "alicloud_kms_key" "kms_software_key_encrypt_decrypt" {
  timeouts {
    delete = "20m" # Specify a deletion timeout period.
  }
  description = "default_key_encrypt_decrypt description"
  # The usage of the key. Default value: ENCRYPT/DECRYPT.
  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 specify this parameter, the key is created in the KMS instance. If you leave the parameter empty, the default key of the CMK type 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 tags that are added to the key for resource mapping. This parameter is optional.
  #tags = {
      #"Environment" = "Production"
      #"Name" = "KMS-01"
      #"SupportTeam" = "PlatformEngineering"
      #"Contact" = "aliyun@test.com"
    #}
}
# The alias of the key is alias/kms_software_key_encrypt_decrypt, which is unique within the Alibaba Cloud account.
resource "alicloud_kms_alias" "kms_software_key_encrypt_decrypt_alias" {
  # The alias of the key.
  alias_name = "alias/kms_software_key_encrypt_decrypt"
  # The ID of the key
  key_id = alicloud_kms_key.kms_software_key_encrypt_decrypt.id
}