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 →
- Accept
kms_key_arn(nullable) as input. - Create the key only if it is null.
- 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.
More on Modules and Code Structure
When do you turn a block of resources into a module, and when do you leave it alone?BeginnerHow do you consume a community module like `terraform-aws-modules/vpc/aws` responsibly?BeginnerAn ECS service module needs the VPC and subnets created by a network module. How do you wire them together?IntermediateHow would you lay out a repo that deploys the same stack to dev, stage and prod?IntermediateHow do you release a shared module so consumers can upgrade at their own pace?IntermediateA module needs to deploy to a second region. Why does putting a provider block inside the module cause trouble?Advanced