<p>I am trying to add a set of annotations based on a variable value.</p>
<p>So far, I am trying to add something like:</p>
<pre><code>annotations = merge({
   annotation1 = value
   annotation2 = value
   try(var.omitAnnotations == false) == null ? {} : {
       annotation3 = value
       annotation4 = value
   }})
</code></pre>
<p>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</p>
<p>How can I get this logic working, so that annotation3 &amp; annotation4 are only added when var.addAnnotations is true?</p>
<p>Thanks in advance!</p>

fuzzi
<p>I would suggest moving any expressions that are too complicated to a local variable, because of visibility:</p>
<pre><code>locals {
   annotations = var.omitAnnotations ? {} : {
       &quot;annotation3&quot; = &quot;value3&quot;
       &quot;annotation4&quot; = &quot;value4&quot;
   }
   add_annotations = try(local.annotations, null)
}
</code></pre>
<p>What this will do is set the <code>local.annotations</code> variable to an empty map if <code>var.omitAnnotations</code> is <code>true</code> or to a map with annotations <code>annotation3</code> and <code>annotation4</code> defined if <code>var.omitAnnotations</code> is <code>false</code>. The local variable <code>add_annotations</code> will then have the value assigned based on using the <code>try</code> built-in function [1]. In the last step, you would just do the following:</p>
<pre><code>annotations = merge(
  {
   &quot;annotation1&quot; = &quot;value1&quot;
   &quot;annotation2&quot; = &quot;value2&quot;
   },
   local.add_annotations
)
</code></pre>
