我需要执行多个相同类型的Kubernetes清单。只有名称、操作和端口更改
mynetworkpolicy.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}"]
)}
需要为每个微服务填充的值
| -------- | -------- | --------------| --------------|
| name | frontend | backend | middleware |
| action | allow | allow | allow |
| ports | 8080,443 | 4731 | 8751,7542 |
示例networkpolicy.yaml
后代
apiVersion: projectcalico.org/v3
kind: GlobalNetworkPolicy
metadata:
name: frontend-policy
spec:
action: allow
rules:
- to:
- operation:
ports: ["8080", "443"]
我怎样才能做到这一点?我不清楚如何写main.tf
resource "kubernetes_manifest" "istio-config" {
manifest = yamldecode(templatefile("${path.module}/networkpolicy.yaml.tpl", {
name =
action =
port =
}))
}
您要查找的是for_each。您可以声明一个局部值块,然后循环遍历该块,替换所需的值。例如:
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)
}
您可以使用loop
menifest = yamldecode(templatefile("${path.module}/networkpolicy.yaml.tpl", {
name = var.name
})
更新networkpolicy.yaml.tpl文件
%{ for s in nameservers ~}
name ${s}
%{ endfor ~}
如果你不想编辑tpl文件,你可以编辑主目录。特遣部队直接
name = <<-EOT
%{ for s in var.name ~}
name ${s}
%{ endfor ~}
EOT
Ref: https://www.terraform.io/language/functions/templatefile
阅读更多关于简单循环的信息:https://blog.gruntwork.io/terraform-tips-tricks-loops-if-statements-and-gotchas-f739bbae55f9
可以使用计数或for_each