<p>I have a manifest yaml file in Terraform to deploy a deployment on a Kubernetes cluster and I want to pass a map having key-value pairs defining node selectors to that yaml file using templatefile function to set <code>nodeSelector</code> on it.</p>
<p>This is how my Terraform code looks like:</p>
<pre><code>...
resource &quot;kubernetes_manifest&quot; &quot;deployment&quot; {
  manifest = yamldecode(
    templatefile(&quot;${path.module}/resources/deployment-tmpl.yaml&quot;,
      {
        app_name      = var.app_name,
        app_namespace = var.app_namespace
    })
  )
}
...
</code></pre>
<p>This is how my manifest yaml code looks like:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app.kubernetes.io/name: ${app_name}
  name: ${app_name}
  namespace: ${app_namespace}
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: ${app_name}
  template:
    metadata:
      labels:
        app.kubernetes.io/name: ${app_name}
    spec:
      containers:
        ...
...
</code></pre>
<p>My node selector variable may look like this:</p>
<pre class="lang-yaml prettyprint-override"><code>variable &quot;node_selector&quot; {
  default = {
    &quot;eks.amazonaws.com/nodegroup&quot; = &quot;app&quot;
  }
}
</code></pre>
<p>My Terraform version is <code>v0.14.11</code>.</p>
<p>How can I do that in my case? I don't want to hardcode and I want to send a map which can have one or more key-value pairs.</p>

Abdullah Khawer
<p>It is possible to do so using <code>yamlencode</code> inside <code>templatefile</code> function in Terraform in this case.</p>
<p>I have changed the manifest yaml file as follows:</p>
<pre class="lang-yaml prettyprint-override"><code>...
    spec:
      nodeSelector:
        ${node_selector}
      containers:
...
</code></pre>
<p>I have changed the Terraform file as follows:</p>
<pre><code>...
resource &quot;kubernetes_manifest&quot; &quot;deployment&quot; {
  manifest = yamldecode(
    templatefile(&quot;${path.module}/resources/deployment-tmpl.yaml&quot;,
      {
        app_name      = var.app_name,
        app_namespace = var.app_namespace,
        node_selector = yamlencode(var.node_selector)
    })
  )
}
...
</code></pre>
<p>Node selector variable will remain the same and can have more than one key-value pair:</p>
<pre class="lang-yaml prettyprint-override"><code>variable &quot;node_selector&quot; {
  default = {
    &quot;eks.amazonaws.com/nodegroup&quot; = &quot;app&quot;
  }
}
</code></pre>
<p>Reference: <a href="https://developer.hashicorp.com/terraform/language/functions/templatefile" rel="nofollow noreferrer">Terraform - templatefile Function</a></p>
