Home > Software design >  Using dynamic Kubernetes annotations in Terraform based on a variable
Using dynamic Kubernetes annotations in Terraform based on a variable

Time:11-19

I am trying to add a set of annotations based on a variable value.

So far, I am trying to add something like:

annotations = merge({
   annotation1 = value
   annotation2 = value
   try(var.omitAnnotations == false) == null ? {} : {
       annotation3 = value
       annotation4 = value
   }})

However, this doesn't appear to be working as expected, and in fact, the annotations are always added, regardless of the value in var.addAnnotations

How can I get this logic working, so that annotation3 & annotation4 are only added when var.addAnnotations is true?

Thanks in advance!

CodePudding user response:

I would suggest moving any expressions that are too complicated to a local variable, because of visibility:

locals {
   annotations = var.omitAnnotations ? {} : {
       "annotation3" = "value3"
       "annotation4" = "value4"
   }
   add_annotations = try(local.annotations, null)
}

What this will do is set the local.annotations variable to an empty map if var.omitAnnotations is true or to a map with annotations annotation3 and annotation4 defined if var.omitAnnotations is false. The local variable add_annotations will then have the value assigned based on using the try built-in function [1]. In the last step, you would just do the following:

annotations = merge(
  {
   "annotation1" = "value1"
   "annotation2" = "value2"
   },
   local.add_annotations
)
  • Related