Categories
Cloud

Create Multiple AWS KMS keys with Terraform

Intro and Aim:

A quick post here as I didn’t find a suitable example online when researching.

The aim is to create multiple CMKs (Customer Managed Keys) in AWS KMS (Key Management Service) with Terraform with unique aliases from a list of variables.

Steps below:

Prerequisites:

Install terraform and set environment variables to connect to my AWS account (rather than entering keys in my terraform code.

export AWS_ACCESS_KEY_ID=<ACCESSKEYID>
export AWS_SECRET_ACCESS_KEY=<SECRET>
export AWS_SESSION_TOKEN=<SESSTOK>

Code:

The key to achieving this aim was the use of count.index in my terraform code to create multiple resources of the same kind, interating through my list of variables.

main.tf:

provider "aws" {
  region = "us-west-2"
}

resource "aws_kms_key" "cmk4istesting" {
  count         = length(var.cmk4istesting) //count will be number of keys
  description   = var.cmk4istesting[count.index]
}

resource "aws_kms_alias" "cmk4istesting-alias" {
  count         = length(var.cmk4istesting-alias) //count will be number of key aliases
  name          = "alias/${var.cmk4istesting-alias[count.index]}"
  target_key_id = "${aws_kms_key.cmk4istesting[count.index].key_id}"
}

variables.tf:

# Do not change the order of these default values. it will force the build to destory and rebuild
variable "cmk4istesting" {
  type = list(any)
  default = [
    "istacey01-cmk",
    "istacey02-cmk",
    "istacey03-cmk",
    "istacey04-cmk",
  ]
}

variable "cmk4istesting-alias" {
  type = list(any)
  default = [
    "istacey01-cmk",
    "istacey02-cmk",
    "istacey03-cmk",
    "istacey04-cmk",
  ]
}

outputs.tf:

output "kms_key_id" {
  value = "${aws_kms_key.cmk4istesting[0].arn}"
}

output "kms_alias_arn" {
  value = "${aws_kms_alias.cmk4istesting-alias[0].arn}"
}

Execution:

Use the terraform commands, init, validate, plan before applying with

terraform apply

The output of terraform apply below:

Check via AWS console:

Here we see the keys created, along with the aliases:

Clean Up:

Run terraform destroy to clean up the resources created:

References:

https://paulkamau.medium.com/terraform-tips-how-to-create-multiple-aws-s3-buckets-with-a-single-resource-config-c89c460a1aa6

https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html

https://www.terraform.io/language/meta-arguments/count

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/kms_key

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/kms_alias