Home > Blockchain >  Terraform: Create multiple Kubernetes manifests using templates
Terraform: Create multiple Kubernetes manifests using templates

Time:06-10

I have a requirement to execute multiple Kubernetes manifests of the same kind. Just names, action, and port changes

my networkpolicy.yaml.tpl

${yamlencode(
    apiVersion: projectcalico.org/v3
    kind: GlobalNetworkPolicy
    metadata:
      name: ${name}-policy
    spec:
      action: ${action}
      rules: 
      - to:
        - operation:
            ports: [for port in ports : "${port}"]
)}
    

values that need to be populated for each microservice

| --------  | -------- | --------------| --------------|
| name      | frontend | backend       | middleware    |
| action    | allow    | allow         | allow         |
| ports     | 8080,443 | 4731          | 8751,7542     |

Example networkpolicy.yaml after generation

    apiVersion: projectcalico.org/v3
    kind: GlobalNetworkPolicy
    metadata:
      name: frontend-policy
    spec:
      action: allow
      rules: 
      - to:
        - operation:
            ports: ["8080", "443"]

how can I achieve this? I am not clear as how-to write main.tf

    resource "kubernetes_manifest" "istio-config" {
      manifest = yamldecode(templatefile("${path.module}/networkpolicy.yaml.tpl", {
        name     =
        action   = 
        port     =  
    }))
  }

CodePudding user response:

What you are looking for is for_each. You can declare a local values block and then loop over that block, replacing what you need. f.e.:

locals {
  services = {
    frontend = {
      action = "allow"
      ports = [8080,433]
    }
    backend = {
      ...
    }
    middleware = {
      ...
    }
  }
}

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

CodePudding user response:

You can use the loop

Example

menifest = yamldecode(templatefile("${path.module}/networkpolicy.yaml.tpl", {
    name = var.name
  })

update the networkpolicy.yaml.tpl file

%{ for s in nameservers ~}
name ${s}
%{ endfor ~}

If you don't want to edit the tpl file you can edit the main.tf directly

name = <<-EOT
    %{ for s in var.name ~}
    name ${s}
    %{ endfor ~}
  EOT

Ref : https://www.terraform.io/language/functions/templatefile

Read more about simple loop : https://blog.gruntwork.io/terraform-tips-tricks-loops-if-statements-and-gotchas-f739bbae55f9

You can use the count or for_each loop to simple make it possible.

  • Related