### Docker Build and Run for Local Development Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/tests/kubestack-starter-kind/README.md This example shows how to build a Docker image for Kubestack and then run it interactively, mounting the current directory as a volume. This enables local development and testing of infrastructure changes. ```shell # Build the container image docker build -t kubestack . # Exec into the container image # add docker socket mount for local dev # -v /var/run/docker.sock:/var/run/docker.sock docker run --rm -ti \ -v `pwd`:/infra \ kubestack ``` -------------------------------- ### Build Terraform Kustomize Provider Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/README.md Compiles the Terraform provider plugin for Kustomize. This command builds the provider binary and places it in the appropriate directory for Terraform to use. Requires Go to be installed. ```makefile make build ``` -------------------------------- ### Provision Kubernetes Manifests using Convenience Module Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/docs/resources/resource.md This example demonstrates provisioning Kubernetes manifests using the `custom-manifests` convenience module. It takes a configuration base key and a nested configuration object that specifies namespaces, resources, and common labels for the Kubernetes resources. ```hcl module "example_custom_manifests" { source = "kbst.xyz/catalog/custom-manifests/kustomization" version = "0.3.0" configuration_base_key = "default" # must match workspace name configuration = { default = { namespace = "example-${terraform.workspace}" resources = [ "${path.root}/manifests/example/namespace.yaml", "${path.root}/manifests/example/deployment.yaml", "${path.root}/manifests/example/service.yaml" ] common_labels = { "env" = terraform.workspace } } } } ``` -------------------------------- ### kustomization_build Data Source Example Usage Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/docs/data-sources/build.md This example demonstrates how to use the `kustomization_build` data source to build a Kustomization from a specified path and configure Kustomize options. ```hcl data "kustomization_build" "test" { path = "test_kustomizations/basic/initial" kustomize_options { load_restrictor = "none" enable_helm = true helm_path = "/path/to/helm" } } ``` -------------------------------- ### Define Kustomize Overlay with Resources and Options Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/docs/data-sources/overlay.md Illustrates the basic usage of the `kustomization_overlay` data source, including specifying `resources` to inherit from or include, and `kustomize_options` such as `load_restrictor`. This example demonstrates how to build a Kustomize overlay by referencing external files and applying Kustomize-specific configurations. ```hcl locals { label_key = "example-label" label_value = true cm_key = "KEY1" cm_value = "VALUE1" } data "template_file" "example" { template = <<-EOT --- config: key1: value1 key2: value2 name: example EOT } data "kustomization_overlay" "example" { common_annotations = { example-annotation: true } common_labels = { (local.label_key) = local.label_value } config_map_generator { name = "example-configmap1" behavior = "create" literals = [ "${local.cm_key}=${local.cm_value}", "filename.yaml=${data.template_file.example.rendered}" ] } resources = [ "path/to/kustomization/to/inherit/from", "path/to/kubernetes/resource.yaml", ] kustomize_options { load_restrictor = "none" } } ``` -------------------------------- ### Git Merge and Push to Main Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/tests/kubestack-starter-kind/README.md This example shows the process of merging approved changes from a feature branch into the 'main' branch and pushing the update. This action applies the changes to the 'ops' environment and triggers a Terraform plan for the 'apps' environment. ```shell # you can merge on the commandline # or by merging a pull request git checkout main git merge examplechange git push origin main ``` -------------------------------- ### Git Tagging for Production Deployment Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/tests/kubestack-starter-kind/README.md This snippet demonstrates how to tag a specific commit on the 'main' branch with a prefix like 'apps-deploy-' to trigger the deployment pipeline for the 'apps' environment. It includes an example of creating a unique tag with a date and counter. ```shell # make sure you're on the correct commit git checkout main git pull git log -1 # if correct, tag the current commit # any tag prefixed with `apps-deploy-` # will trigger the pipeline git tag apps-deploy-$(date -I)-0 # in case of multiple deploys on the same day, # increase the counter # e.g. git tag apps-deploy-2020-05-14-1 ``` -------------------------------- ### Build Kubernetes Manifests from Kustomization Directory Source: https://context7.com/kbst/terraform-provider-kustomization/llms.txt Demonstrates using the `kustomization_build` data source to generate Kubernetes manifests from a specified Kustomize directory. It includes basic usage and an advanced example with `kustomize_options` for features like Helm chart inflation. The snippet also shows how to deploy these resources using `kustomization_resource` and access output values. ```hcl # Basic usage: Build from a directory containing kustomization.yaml data "kustomization_build" "example" { path = "./kubernetes/overlays/production" } # With kustomize options enabled data "kustomization_build" "advanced" { path = "./kubernetes/base" kustomize_options { load_restrictor = "LoadRestrictionsNone" # Allow loading from outside path enable_alpha_plugins = false enable_exec = false enable_helm = true # Enable Helm chart inflation enable_star = false helm_path = "/usr/local/bin/helm" } } # Deploy all resources from the kustomization resource "kustomization_resource" "example" { for_each = data.kustomization_build.example.ids manifest = data.kustomization_build.example.manifests[each.value] wait = true # Wait for resources to become ready } # Access outputs output "resource_ids" { value = data.kustomization_build.example.ids # Returns: Set of resource IDs like ["apps/Deployment/default/nginx", "_/Service/default/nginx"] } output "resource_manifests" { value = data.kustomization_build.example.manifests # Returns: Map of resource ID to YAML manifest string } output "prioritized_ids" { value = data.kustomization_build.example.ids_prio # Returns: List of sets ordered by creation priority (e.g., namespaces before deployments) } ``` -------------------------------- ### Provision Kubernetes Resources with Explicit Dependencies and Conditional Sensitivity Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/docs/resources/resource.md This example showcases provisioning Kubernetes resources using the `kustomization_resource` and `kustomization_build` data source. It illustrates explicit `depends_on` for ordered resource application and conditional `sensitive` attribute handling for Kubernetes secrets to prevent plan leakage. ```hcl data "kustomization_build" "test" { path = "kustomize/test_kustomizations/basic/initial" } # first loop through resources in ids_prio[0] resource "kustomization_resource" "p0" { for_each = data.kustomization_build.test.ids_prio[0] manifest = ( contains(["_/Secret"], regex("(?P.*/.*)/.*/.*", each.value)["group_kind"]) ? sensitive(data.kustomization_build.test.manifests[each.value]) : data.kustomization_build.test.manifests[each.value] ) } # then loop through resources in ids_prio[1] # and set an explicit depends_on on kustomization_resource.p0 # wait 2 minutes for any deployment, statefulset or daemonset to become ready resource "kustomization_resource" "p1" { for_each = data.kustomization_build.test.ids_prio[1] manifest = ( contains(["_/Secret"], regex("(?P.*/.*)/.*/.*", each.value)["group_kind"]) ? sensitive(data.kustomization_build.test.manifests[each.value]) : data.kustomization_build.test.manifests[each.value] ) wait = true timeouts { create = "2m" update = "2m" } depends_on = [kustomization_resource.p0] } # finally, loop through resources in ids_prio[2] ``` -------------------------------- ### Replace Secret Value with Kustomization Overlay Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/docs/data-sources/overlay.md An example demonstrating how to use Kustomization overlays to replace a specific field value, such as an environment variable in a container, with data from a Kubernetes Secret. ```hcl data "kustomization_overlay" "example" { resources = [ "path/to/kustomization", ] replacements { source { kind = "Secret" name = "my-secret" } target { select { name = "hello" kind = "Job" } field_paths = [ "spec.template.spec.containers.[name=hello].env.[name=SECRET_TOKEN].value" } } } ``` -------------------------------- ### Attach to Running Terraform Provider Process for Debugging (Go, JSON, Shell) Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/README.md Debug the kustomize Terraform provider by running it with delve and attaching your IDE. This involves starting the provider in debug mode with `dlv exec`, configuring your IDE (e.g., VS Code) to attach to the delve server, and setting the `TF_REATTACH_PROVIDERS` environment variable in your Terraform terminal. ```shell PLUGIN_PROTOCOL_VERSIONS=5 dlv exec --api-version=2 --listen=127.0.0.1:49188 --headless /path/to/terraform-provider-kustomization/terraform-provider-kustomize -- --debug ``` ```json { "name": "Connect to server", "type": "go", "request": "attach", "mode": "remote", "remotePath": "${workspaceFolder}", "port": 49188, "host": "127.0.0.1", "apiVersion": 2, "env": { "KUBECONFIG_PATH": "${HOME}/.kube/config" }, "dlvLoadConfig": { "followPointers": true, "maxVariableRecurse": 1, "maxStringLen": 512, "maxArrayValues": 64, "maxStructFields": -1 } } ``` ```shell export TF_REATTACH_PROVIDERS="{"registry.terraform.io/kbst/kustomization":{"Protocol":"grpc","Pid":13366,"Test":true,"Addr":{"Network":"unix","String":"/var/folders/7c/wdp684z11w1_6cj0d6lgl8hw0000gn/T/plugin2650218557"}}}" ``` -------------------------------- ### Basic Terraform Commands Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/tests/kubestack-starter-kind/README.md This snippet includes essential Terraform commands, 'terraform init' to initialize the working directory and 'terraform plan' to generate an execution plan. These are fundamental steps for managing infrastructure with Terraform in Kubestack. ```shell # run terraform init terraform init # run, e.g. terraform plan terraform plan ``` -------------------------------- ### Git Checkout and Branching for Changes Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/tests/kubestack-starter-kind/README.md This snippet demonstrates how to checkout a new branch from 'main' to begin making configuration changes in a Git repository, a crucial first step in the Kubestack GitOps process. ```shell # checkout a new branch from main git checkout -b examplechange main # make your changes # commit your changes git commit # write a meaningful commit message # push your changes git push origin examplechange ``` -------------------------------- ### Add Kustomize Components to Overlay Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/docs/data-sources/overlay.md Shows how to include Kustomize components in an overlay definition using the `components` argument within the `kustomization_overlay` data source. This allows inheriting configurations from separate Kustomize component directories. ```hcl data "kustomization_overlay" "example" { components = [ "path/to/component", "path/to/another/component" ] } ``` -------------------------------- ### Configure Kustomize Overlay Labels Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/docs/data-sources/overlay.md Demonstrates how to set Kustomize `labels` using the `labels` block within the `kustomization_overlay` data source. It shows how to define key-value pairs for labels and optionally include them as selectors, using local variables for dynamic label values. ```hcl # example shows how keys and values can be references locals { label_key = "example-label" label_value = true } data "kustomization_overlay" "example" { labels { pairs = { (local.label_key) = local.label_value } include_selectors = true # <-- false by default } } ``` -------------------------------- ### Import Existing Kustomize Resources into Terraform Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/docs/index.md This command demonstrates how to import an existing Kubernetes resource managed by Kustomize into the Terraform state. The resource must have a `kubectl.kubernetes.io/last-applied-configuration` annotation. ```shell terraform import 'kustomization_resource.test["apps/Deployment/test-namespace/test-deployment"]' apps/Deployment/test-namespace/test-deployment ``` -------------------------------- ### Deploy Application Resources using Kustomization Overlay Source: https://context7.com/kbst/terraform-provider-kustomization/llms.txt Deploys Kubernetes application resources based on a Kustomize overlay. It iterates over the IDs generated by the `kustomization_overlay` data source, applying manifests and optionally waiting for deployment completion based on the environment. It also specifies timeouts for resource operations and has a dependency on the namespace resource. ```terraform resource "kustomization_resource" "app" { for_each = data.kustomization_overlay.app.ids manifest = data.kustomization_overlay.app.manifests[each.value] wait = var.environment == "production" ? true : false timeouts { create = "10m" update = "10m" delete = "15m" } depends_on = [kustomization_resource.namespace] } ``` -------------------------------- ### kustomization_overlay - Replacements Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/docs/data-sources/overlay.md Demonstrates how to use the `replacements` block to modify fields within resources, exemplified by replacing an environment variable value in a container. ```APIDOC ## kustomization_overlay - Replacements ### Description Used to define replacements for fields within Kubernetes resources managed by Kustomize. This is analogous to Kustomize's `commonAnnotations`, `commonLabels`, `patchesJson6902`, `patchesStrategicMerge`, and `replacements` functionalities. ### Method Not Applicable (Data Source Configuration) ### Endpoint Not Applicable (Terraform Data Source) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ##### Options Attributes When referencing a field path, or field paths, `options` can be used to access a sub-component of the path. - `delimiter` (string) - Optional - Used to split a field. - `index` (number) - Optional - Used to choose which portion of the split to take (default 0). - `create` (bool) - Optional - Whether to add a target field if it is missing. ### Request Example ```hcl data "kustomization_overlay" "example" { resources = [ "path/to/kustomization", ] replacements { source { kind = "Secret" name = "my-secret" } target { select { name = "hello" kind = "Job" } field_paths = [ "spec.template.spec.containers.[name=hello].env.[name=SECRET_TOKEN].value" ] } } } ``` ### Response #### Success Response (200) This is a Terraform data source, it does not produce a direct HTTP response. The configuration is used by Terraform to manage Kustomize resources. #### Response Example ```json { "message": "Configuration applied successfully" } ``` ``` -------------------------------- ### Git Commit and Push for Review Updates Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/tests/kubestack-starter-kind/README.md This code block illustrates how to commit and push subsequent changes made to a branch after a review, ensuring that feedback is incorporated into the proposed updates before merging. ```shell # make sure you're in the correct branch git checkout examplechange # make changes required by the review # commit and push the required changes git commit # write a meaningful commit message git push origin examplechange ``` -------------------------------- ### Launch Specific Terraform Provider Test Function for Debugging (Go, JSON) Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/README.md Debug a specific test function within the kustomize Terraform provider by configuring your IDE (e.g., VS Code) to launch the test in debug mode. This involves setting up a `launch.json` configuration with the `request` type as `launch` and `mode` as `test`, specifying the program, environment variables, and test arguments. ```json { "name": "Launch test function", "type": "go", "request": "launch", "mode": "test", "program": "${workspaceFolder}/kustomize", "env": { "TF_ACC": "1", "KUBECONFIG_PATH": "${env:HOME}/.kube/config" }, "args": [ "-test.v", "-test.run", "^TestFunctionNameGoesHere$" ], } ``` -------------------------------- ### Configure Kustomize Overlay with ConfigMap Generator Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/docs/data-sources/overlay.md Shows how to define and configure a Kustomize `configMapGenerator` within a `kustomization_overlay` data source. It illustrates setting literals, referencing rendered templates from a `template_file` data source, and applying generator options like disabling name suffix hashing. This allows for dynamic generation of ConfigMaps based on Terraform inputs. ```hcl locals { cm_key = "KEY1" cm_value = "VALUE1" } data "template_file" "example" { template = <<-"EOT" --- config: key1: value1 key2: value2 name: example EOT } data "kustomization_overlay" "example" { # a first ConfigMap config_map_generator { name = "example-configmap1" behavior = "create" literals = [ "${local.cm_key}=${local.cm_value}", "filename.yaml=${data.template_file.example.rendered}" ] options { disable_name_suffix_hash = true } } # a second ConfigMap config_map_generator { name = "example-configmap2" literals = [ "KEY1=VALUE1", "KEY2=VALUE2" ] envs = [ "path/to/properties.env" ] files = [ "path/to/config/file.cfg" ] } } ``` -------------------------------- ### Cloud Provider Authentication Commands Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/tests/kubestack-starter-kind/README.md This section provides the necessary commands to authenticate with major cloud providers (AWS, Azure, GCP) within the Kubestack container environment. These commands ensure that Terraform and cloud CLIs can access and manage resources. ```shell # for AWS aws configure # for Azure az login # for GCP gcloud init gcloud auth application-default login ``` -------------------------------- ### Define Kustomize Overlay with Common Annotations and Labels Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/docs/data-sources/overlay.md Demonstrates how to configure common annotations and labels for a Kustomize overlay using the `kustomization_overlay` data source. This is useful for applying consistent metadata across generated Kubernetes resources. It uses local variables for dynamic label values. ```hcl locals { label_key = "example-label" label_value = true } data "kustomization_overlay" "example" { common_annotations = { example-annotation = true } common_labels = { (local.label_key) = local.label_value } } ``` -------------------------------- ### Configure Helm Globals for Kustomize Overlay (HCL) Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/docs/data-sources/overlay.md Sets global configurations for Helm within a Kustomize overlay, such as `chart_home` and `config_home` directories. This requires enabling Helm support via `kustomize_options.enable_helm`. It works in conjunction with `helm_charts` to manage chart inflation and Kustomize's Helm-related directories. ```hcl data "kustomization_overlay" "minecraft" { helm_globals { chart_home = "/local/chart/path/" } helm_charts { # this is relative to `chart_home` (eg: ${chart_home}/charts/${name}) name = "minecraft" version = "3.1.3" release_name = "moria" values_inline = < migrate.py <<'EOF' import sys import re for si in sys.stdin.readlines(): if not "kustomization_resource" in si: continue so = re.sub(r"(.*)\[\"([^_]*)\_[^_]*\_([^|]*)\|([^|]*)\|([^\"]*)\"]", r'\1["\2/\3/\4/\5"]', si) so = re.sub(r"\~[GX]", r"_", so) print(f"terraform state mv '{si.strip()}' '{so.strip()}'") EOF terraform state list | python3 migrate.py > state_mv.sh bash state_mv.sh ``` -------------------------------- ### Configure Generator Options for Kustomize Overlay (HCL) Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/docs/data-sources/overlay.md Sets options for all generators within a Kustomize overlay. This includes adding labels, annotations, and controlling hash suffix generation. It's an optional configuration block. ```hcl data "kustomization_overlay" "example" { generator_options { labels = { example-label = "example" } annotations = { example-annotation = "example" } disable_name_suffix_hash = true } } ``` -------------------------------- ### Apply Kustomize Transformers Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/docs/data-sources/overlay.md Specifies paths to Kustomization transformer files, allowing for modification of Kubernetes resources as part of the Kustomize build process. ```hcl data "kustomization_overlay" "example" { transformers = [ "path/to/kustomization/transformer.yaml" ] } ``` -------------------------------- ### Configure Kustomize Replacements for Overlay (HCL) Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/docs/data-sources/overlay.md Defines Kustomize replacements to modify Kubernetes resources. Replacements can be specified via a file path or by defining source and target selectors, including field paths. This is an optional configuration block. ```hcl # Example with path to replacements file: data "kustomization_overlay" "example_path" { replacements { path = "path/to/replacements.yaml" } } # Example with source and target selectors: data "kustomization_overlay" "example_selectors" { replacements { source { kind = "Deployment" name = "my-app" field_path = "metadata.labels.version" } target { select { kind = "Service" name = "my-app-service" } field_paths = ["spec.selector.version"] } } } ``` -------------------------------- ### Set Kustomize Replicas for Resources Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/docs/data-sources/overlay.md Allows setting the number of replicas for specified Kubernetes resources. This is useful for managing the scaling of deployments, statefulsets, etc. ```hcl data "kustomization_overlay" "example" { replicas { name = "example-deployment" count = 3 } replicas { name = "example-statefulset" count = 5 } } ``` -------------------------------- ### Output Deployed Resource IDs and Namespace Source: https://context7.com/kbst/terraform-provider-kustomization/llms.txt Defines Terraform outputs for the deployed Kubernetes resource IDs and the created namespace. These outputs provide visibility into the applied resources and the target namespace name after the Terraform apply. ```terraform output "deployed_resources" { value = data.kustomization_overlay.app.ids } output "namespace" { value = "${var.environment}-app" } ``` -------------------------------- ### Configure Kustomize Patches for Overlay (HCL) Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/docs/data-sources/overlay.md Defines Kustomize patches to modify Kubernetes resources. Patches can be specified by path or as inline strings, with options to target specific resources and control name/kind changes. This is an optional configuration block. ```hcl data "kustomization_overlay" "example" { resources = [ "path/to/kustomization", ] patches { path = "path/to/patch.yaml" target { label_selector = "app=example,env=${terraform.workspace}" } } patches { target { kind = "Namespace" name = "test-ns" } patch = <<-EOF kind: Namespace metadata: name: new-ns EOF options { allow_name_change = true } } patches { patch = <<-EOF - op: replace path: /spec/rules/0/http/paths/0/path value: /newpath EOF target { group = "networking.k8s.io" version = "v1beta1" kind = "Ingress" name = "example" namespace = "example-basic" annotation_selector = "nginx.ingress.kubernetes.io/rewrite-target" } } } ``` -------------------------------- ### Configure Kustomize Terraform Provider Source: https://github.com/kbst/terraform-provider-kustomization/blob/master/docs/index.md This block configures the Kustomize provider, specifying the source and version. It also sets up authentication by defining one of `kubeconfig_path`, `kubeconfig_raw`, or `kubeconfig_incluster`. ```hcl terraform { required_providers { kustomization = { source = "kbst/kustomization" version = "0.9.0" } } } provider "kustomization" { # one of kubeconfig_path, kubeconfig_raw or kubeconfig_incluster must be set # kubeconfig_path = "~/.kube/config" # can also be set using KUBECONFIG_PATH environment variable # kubeconfig_raw = data.template_file.kubeconfig.rendered # kubeconfig_raw = yamlencode(local.kubeconfig) # kubeconfig_incluster = true } ```