Interview Prep/Terraform/Modules and Code Structure

A module should optionally create a KMS key, or use an existing one. How do you design that interface?

AdvancedScenarioModules and Code Structure
Answer

Situation read → "Create or bring your own" is a very common module requirement.

What I'd do →

  1. Accept kms_key_arn (nullable) as input.
  2. Create the key only if it is null.
  3. Expose the effective ARN as a local.
variable "kms_key_arn" {
  type    = string
  default = null
}
resource "aws_kms_key" "this" {
  count               = var.kms_key_arn == null ? 1 : 0
  enable_key_rotation = true
}
locals {
  kms_key_arn = coalesce(var.kms_key_arn, one(aws_kms_key.this[*].arn))
}

Why → The caller expresses intent with one optional value, and the rest of the module uses local.kms_key_arn with no branching.

Interview tip → The condition must depend on a value known at plan time, not on another resource's ID.

All Terraform questions Roadmap: Terraform

More on Modules and Code Structure