What I am trying to do?
I want to create a kubernetes service object using terraform, but make it re-usable. So everytime there's a new service, I could just append the variables.
My problem:
I have been reading and trying different things but I am not sure how would I loop over "annotations" and "selectors" which will have more than one key value pair.
Code Example
Variables.tf using which I want to build the actual terraform resource.
variable "apps" {
default = {
"app1" = {
svc_name = "app1"
namespace = "testns"
annotations = {
"testannotation" = "ann1"
}
selector = {
app = "podinfo"
env = "dev"
}
ports = {
name = "http"
port = 80
protocol = "TCP"
targetPort = 8008
}
},
"app2" = {
svc_name = "app2"
namespace = "testns"
annotations = {
"testannotation" = "ann1"
}
selector = {
app = "someapp"
env = "qa"
}
ports = {
name = "http"
port = 8080
protocol = "TCP"
targetPort = 8080
}
},
}
}
Here is the main.tf where I want to loop over "annotations" and "selectors" of the variables because there could be more than one of them. BUT there is only one "annotations" and "selector" block. So I couldn't use "dynamic" as it will generate many of those blocks.
resource "kubernetes_service" "service" {
for_each = var.apps
metadata {
name = each.value.svc_name
namespace = each.value.namespace
# annotations = {
# HOW DO I GET THE ANNOTATIONS HERE
# }
}
spec {
selector = {
## HOW DO I GET THE SELECTORS FROM VARIABLEES HERE
}
session_affinity = "ClientIP"
port {
port = each.value.ports.port
target_port = each.value.ports.targetPort
}
type = "ClusterIP"
}
}
I'd appreciate any guide, links or suggestions here!
CodePudding user response:
You do the same as with other properties:
resource "kubernetes_service" "service" {
for_each = var.apps
metadata {
name = each.value.svc_name
namespace = each.value.namespace
annotations = each.value.annotations
}
spec {
selector = each.value.selector
session_affinity = "ClientIP"
port {
port = each.value.ports.port
target_port = each.value.ports.targetPort
}
type = "ClusterIP"
}
}