Files
Terraform_kube/cronjob.tf.20260813
T
2026-08-14 12:08:00 +01:00

120 lines
3.5 KiB
Plaintext

variable "cronjob" {
type = map(object({
name = optional(string)
image = string
enabled = bool
namespace = optional(string)
connected_namespace = optional(string, "")
schedule = string
command = optional(list(string))
args = optional(list(string))
pvc = optional(map(object({
name = string
pvc = optional(bool, false)
config_map = optional(bool, false)
secret = optional(bool, false)
host_path = optional(string)
pvc_size = optional(string)
storage_class_name = optional(string, "nfs-storage-intelligent")
annotations_fileType = optional(string)
existing_pvc = optional(bool, false)
mount_path = string
sub_path = optional(string)
})))
}))
}
locals {
pvc_list = flatten([
for key, value in var.cronjob : [
for index, pvc in value.pvc : {
key = "${coalesce(value.namespace, value.connected_namespace, key)}/${pvc.name}"
index = index
pvc = pvc.pvc
name = pvc.name
pvc_size = pvc.pvc_size
mount_path = pvc.mount_path
storage_class_name = pvc.storage_class_name
annotations_fileType = pvc.annotations_fileType
existing_pvc = pvc.existing_pvc
sub_path = pvc.sub_path
namespace = coalesce(value.namespace, value.connected_namespace, key)
}] if value.enabled == true && value.pvc != null
])
# group duplicates instead of throwing an error
pvc_map_grouped = {
for p in local.pvc_list :
p.key => p...
}
# keep only one PVC per key (take the first)
pvc_map = {
for k, list in local.pvc_map_grouped :
k => list[0]
}
pvc_details = values(local.pvc_map)
}
resource "kubernetes_persistent_volume_claim_v1" "automatic-pvc-cronjob" {
for_each = { for key, value in local.pvc_details : "${value.index}" => merge(value, { mew_key = value.index }) if value.pvc && value.existing_pvc != true }
metadata {
namespace = coalesce(each.value.namespace, each.key)
name = "${each.value.name}-pvc"
labels = {
deployment_method = "Terraform"
}
annotations = {
fileType = try(each.value.annotations_fileType, "file")
}
}
spec {
access_modes = ["ReadWriteMany"]
storage_class_name = each.value.storage_class_name
resources {
requests = {
storage = each.value.pvc_size
}
}
}
}
resource "kubernetes_cron_job_v1" "automatic_cronjob" {
for_each = { for key, value in var.cronjob : key => value if value.enabled == true }
metadata {
name = "${each.key}-cronjob"
namespace = coalesce(each.value.namespace, each.value.connected_namespace, each.key)
labels = {
app = each.key
deployment_method = "Terraform"
}
}
spec {
schedule = each.value.schedule
job_template {
metadata {}
spec {
template {
metadata {}
spec {
container {
name = coalesce(each.value.name, each.key)
image = each.value.image
command = each.value.command != null ? each.value.command : []
args = each.value.args != null ? each.value.args : []
}
}
}
}
}
}
}