<p>I have a requirement to execute multiple Kubernetes manifests of the same kind. Just names, action, and port changes</p>
<p>my <code>networkpolicy.yaml.tpl</code></p>
<pre><code>${yamlencode(
    apiVersion: projectcalico.org/v3
    kind: GlobalNetworkPolicy
    metadata:
      name: ${name}-policy
    spec:
      action: ${action}
      rules: 
      - to:
        - operation:
            ports: [for port in ports : &quot;${port}&quot;]
)}
    
</code></pre>
<p>values that need to be populated for each microservice</p>
<pre><code>| --------  | -------- | --------------| --------------|
| name      | frontend | backend       | middleware    |
| action    | allow    | allow         | allow         |
| ports     | 8080,443 | 4731          | 8751,7542     |
</code></pre>
<p>Example <code>networkpolicy.yaml</code> after generation</p>
<pre><code>    apiVersion: projectcalico.org/v3
    kind: GlobalNetworkPolicy
    metadata:
      name: frontend-policy
    spec:
      action: allow
      rules: 
      - to:
        - operation:
            ports: [&quot;8080&quot;, &quot;443&quot;]
</code></pre>
<p>how can I achieve this? I am not clear as how-to write <code>main.tf</code></p>
<pre><code>    resource &quot;kubernetes_manifest&quot; &quot;istio-config&quot; {
      manifest = yamldecode(templatefile(&quot;${path.module}/networkpolicy.yaml.tpl&quot;, {
        name     =
        action   = 
        port     =  
    }))
  }
</code></pre>

Eva
<p>What you are looking for is <a href="https://www.terraform.io/language/meta-arguments/for_each" rel="nofollow noreferrer">for_each</a>. You can declare a <a href="https://www.terraform.io/language/values/locals" rel="nofollow noreferrer">local values block</a> and then loop over that block, replacing what you need. f.e.:</p>
<pre><code>locals {
  services = {
    frontend = {
      action = &quot;allow&quot;
      ports = [8080,433]
    }
    backend = {
      ...
    }
    middleware = {
      ...
    }
  }
}

resource &quot;kubernetes_manifest&quot; &quot;istio-config&quot; {
  for_each = local.services
  manifest = yamldecode(templatefile(&quot;${path.module}/networkpolicy.yaml.tpl&quot;, each.value)
}

</code></pre>
