Bootstrap FreeKB - Amazon Web Services (AWS) - List Key Management Service (KMS) Keys using Terraform
Amazon Web Services (AWS) - List Key Management Service (KMS) Keys using Terraform


Let's say you have a key named default-kms-key.

 

Let's say you have the following files on your Terraform server.

├── required_providers.tf
├── key_management_services (directory)
│   ├── data.tf
│   ├── outputs.tf
│   ├── provider.tf
│   ├── resources.tf

 

required_providers.tf will almost always have this.

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
    }
  }
}

 

Let's say provider.tf has the following. In this example, the "default" profile in /home/username/.aws/config and /home/username/.aws/credentials is being used. This assumes you have setup Terraform as described in Amazon Web Services (AWS) - Getting Started with Terraform.

provider "aws" {
  alias   = "default"
  profile = "default"
  region  = "default"
}

 

And modules.tf could have something like this.

module "key_management_services" {
  source = "./key_management_services"
}

 

And data.tf in your key_management_services module could have something like this. The alias is default-kms-key since that is the alias of the key in this example.

data "aws_kms_key" "my_aws_kms_key" {
  key_id = "alias/default-kms-key"
}

 

And outputs.tf in your key_management_services module could have something like this.

output "kms-keys" {
  value = data.aws_kms_key.my_aws_kms_key
}

 

And outputs.tf in the base directory of your root module could have the following.

output "kms-keys" {
  value = module.key_management_services.kms-keys
}

 

The terraform refresh command can be used to produce output, which should return something like this.

kms-keys = {
  "arn" = "arn:aws:kms:us-east-1:123456789012:key/72b03a04-b45d-4ea5-b720-ef3324efd774"
  "aws_account_id" = "123456789012"
  "creation_date" = "2022-09-30T10:04:33Z"
  "customer_master_key_spec" = "SYMMETRIC_DEFAULT"
  "deletion_date" = tostring(null)
  "description" = "default KMS key"
  "enabled" = true
  "expiration_model" = ""
  "grant_tokens" = tolist(null) /* of string */
  "id" = "72b03a04-b45d-4ea5-b720-ef3324efd774"
  "key_id" = "alias/default-kms-key"
  "key_manager" = "CUSTOMER"
  "key_state" = "Enabled"
  "key_usage" = "ENCRYPT_DECRYPT"
  "multi_region" = false
  "multi_region_configuration" = tolist([])
  "origin" = "AWS_KMS"
  "valid_to" = tostring(null)
}

 

And here is how you could output the value of a certain key (the "arn" key in this example).

output "kms-arn-key" {
  value = data.aws_kms_key.my_aws_kms_key.arn
}

 

Which should return the following.

kms-arn-key = "arn:aws:kms:us-east-1:123456789012:key/72b03a04-b45d-4ea5-b720-ef3324efd774"

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter f28d72 in the box below so that we can be sure you are a human.