terraform { required_version = ">= 1.6.0" required_providers { kubectl = { source = "gavinbunney/kubectl" version = ">= 1.14.0" } } } provider "kubectl" { config_path = var.kubeconfig_path != "" ? var.kubeconfig_path : null host = var.kubeconfig_path == "" ? var.k3s_server_url : null token = var.kubeconfig_path == "" ? var.k3s_token : null insecure = var.kubeconfig_path == "" ? true : false } locals { manifest_dir = "${path.module}/manifests" manifest_files = fileset(local.manifest_dir, "**/*.yaml") raw_documents = flatten([ for f in local.manifest_files : [ for doc in split("\n---", trimspace(file("${local.manifest_dir}/${f}"))) : trimspace(doc) if trimspace(doc) != "" ] ]) # Kinds that are not real Kubernetes API objects and must be excluded skip_kinds = toset([ "Kustomization", ]) # apiVersion prefixes for CRDs that may not be installed yet skip_api_prefixes = toset([ "barmancloud.cnpg.io/", ]) decoded_documents = [ for doc in local.raw_documents : yamldecode(doc) if( try(yamldecode(doc).kind, "") != "" && !contains(local.skip_kinds, try(yamldecode(doc).kind, "")) && !anytrue([for p in local.skip_api_prefixes : startswith(try(yamldecode(doc).apiVersion, ""), p)]) ) ] cluster_scoped_kinds = toset([ "Namespace", "CustomResourceDefinition", "ClusterRole", "ClusterRoleBinding", "ClusterIssuer", "PersistentVolume", "StorageClass", "MutatingWebhookConfiguration", "ValidatingWebhookConfiguration", ]) namespaced_documents = [ for m in local.decoded_documents : merge( m, { metadata = merge( lookup(m, "metadata", {}), { for k, v in { namespace = var.namespace } : k => v if !contains(local.cluster_scoped_kinds, m.kind) } ) } ) ] # Convert back to YAML for kubectl_manifest manifest_yamls = { for idx, m in local.namespaced_documents : tostring(idx) => yamlencode(m) } } resource "kubectl_manifest" "namespace" { yaml_body = yamlencode({ apiVersion = "v1" kind = "Namespace" metadata = { name = var.namespace } }) server_side_apply = true force_conflicts = true } resource "kubectl_manifest" "resources" { for_each = local.manifest_yamls yaml_body = each.value server_side_apply = true force_conflicts = true wait_for_rollout = false depends_on = [kubectl_manifest.namespace] }