mRyan
mRyan

Reputation: 390

Terraform map require key to be set and accept any optional keys

I want to allow any key to be set within a dictionary object and require Name to be set. Im passing this object into a variable that forces Name to be set but its ignoring all the other keys

tags   = {
  "Name"        = "EC2_Name_Value"  # Required
  "AnyKey1"        = "value1"
  "AnyKey2"        = "value2"
...
}

variable "tags" {
  type = object({
    Name = string
  })
}
> var.tags
{
  "Name" = "EC2_Name_Value"
}

I know that I'm able to use key = optional(string) however, i want to accept all extra keys and not have to define only the keys i want to accept.

Upvotes: 0

Views: 1292

Answers (1)

Marko E
Marko E

Reputation: 18108

What I would suggest is leaving the tags variable as is (maybe renaming it), and then using either an additional variable or local variables, e.g.:

variable "required_tag" {
  type = object({
    Name = string
  })
}

variable "additional_tags" {
  type = object(any)
}

Then, you would use the merge built-in function [1] to bring them all together:

tags = merge(var.required_tag, var.additional_tags)

Alternatively, since you know you will always need that one tag, you could switch it up a bit and remove the required_tag (or tags in your example) variable, and do something like:

tags = merge({ Name = "EC2_Name_Value" }, var.additional_tags)

Last, but not the least, there is an option to use default_tags on the provider level [2], but I am not sure if that fits your case.


[1] https://developer.hashicorp.com/terraform/language/functions/merge

[2] https://registry.terraform.io/providers/hashicorp/aws/latest/docs/guides/resource-tagging#propagating-tags-to-all-resources

Upvotes: 3

Related Questions