├── .github └── workflows │ └── main.yml ├── .gitignore ├── .goreleaser-build.yml ├── .goreleaser.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── Makefile ├── README.md ├── assets └── favicon.png ├── docs ├── data-sources │ ├── build.md │ └── overlay.md ├── index.md └── resources │ └── resource.md ├── go.mod ├── go.sum ├── kustomize ├── data_source_kustomization.go ├── data_source_kustomization_build.go ├── data_source_kustomization_build_test.go ├── data_source_kustomization_overlay.go ├── data_source_kustomization_overlay_fs.go ├── data_source_kustomization_overlay_fs_test.go ├── data_source_kustomization_overlay_test.go ├── data_source_kustomization_test.go ├── manifest.go ├── manifest_test.go ├── provider.go ├── provider_test.go ├── resource_kustomization.go ├── resource_kustomization_test.go ├── resource_kustomization_waitfor.go ├── structures_kustomization.go ├── structures_kustomization_test.go ├── test_kustomizations │ ├── _example_app │ │ ├── deployment.yaml │ │ ├── ingress.yaml │ │ ├── kustomization.yaml │ │ └── service.yaml │ ├── _test_files │ │ ├── cmGenerator.yaml │ │ ├── deployment_patch_env.yaml │ │ └── properties.env │ ├── basic │ │ ├── initial │ │ │ ├── kustomization.yaml │ │ │ └── namespace.yaml │ │ └── modified │ │ │ ├── deployment2.yaml │ │ │ └── kustomization.yaml │ ├── component │ │ └── Kustomization │ ├── crd │ │ ├── initial │ │ │ ├── co.yaml │ │ │ ├── crd.yaml │ │ │ ├── kustomization.yaml │ │ │ └── namespace.yaml │ │ └── modified │ │ │ ├── co-patch-clustered.yaml │ │ │ ├── co-patch-namespaced.yaml │ │ │ └── kustomization.yaml │ ├── fail_namespace_not_allowed │ │ ├── invalid_cluster_role_binding.yaml │ │ └── kustomization.yaml │ ├── fail_namespace_required │ │ ├── invalid_role_binding.yaml │ │ └── kustomization.yaml │ ├── fail_plan_invalid │ │ ├── invalid_cluster_role_binding.yaml │ │ └── kustomization.yaml │ ├── helm │ │ └── initial │ │ │ ├── alt-values.yaml │ │ │ ├── charts │ │ │ ├── test-basic │ │ │ │ ├── Chart.yaml │ │ │ │ ├── crds │ │ │ │ │ └── crontabs.yaml │ │ │ │ ├── templates │ │ │ │ │ ├── _helpers.tpl │ │ │ │ │ ├── deployment.yaml │ │ │ │ │ ├── ingress.yaml │ │ │ │ │ ├── service.yaml │ │ │ │ │ └── tests │ │ │ │ │ │ └── test-connection.yaml │ │ │ │ └── values.yaml │ │ │ ├── test-capabilities │ │ │ │ ├── Chart.yaml │ │ │ │ ├── templates │ │ │ │ │ ├── _helpers.tpl │ │ │ │ │ └── configmap.yaml │ │ │ │ └── values.yaml │ │ │ └── test-releasename │ │ │ │ ├── Chart.yaml │ │ │ │ ├── templates │ │ │ │ ├── _helpers.tpl │ │ │ │ ├── deployment.yaml │ │ │ │ ├── ingress.yaml │ │ │ │ └── service.yaml │ │ │ │ └── values.yaml │ │ │ ├── kustomization.yaml │ │ │ ├── merge-values.yaml │ │ │ └── namespace.yaml │ ├── nowait │ │ ├── initial │ │ │ ├── daemonset.yaml │ │ │ ├── kustomization.yaml │ │ │ ├── namespace.yaml │ │ │ └── statefulset.yaml │ │ └── modified │ │ │ └── kustomization.yaml │ ├── replacements │ │ ├── configmap.yaml │ │ ├── kustomization.yaml │ │ ├── namespace.yaml │ │ ├── replacements.yaml │ │ ├── target1.yaml │ │ ├── target2.yaml │ │ └── target3.yaml │ ├── secret_service_account_token │ │ ├── Kustomization │ │ ├── namespace.yaml │ │ ├── secret_default.yaml │ │ ├── secret_sa_token.yaml │ │ └── service_account.yaml │ ├── transformer_configs │ │ ├── initial │ │ │ ├── kustomization.yaml │ │ │ └── namespace.yaml │ │ └── modified │ │ │ ├── kustomization.yaml │ │ │ └── label.yaml │ ├── update_inplace │ │ ├── initial │ │ │ ├── kustomization.yaml │ │ │ └── namespace.yaml │ │ └── modified │ │ │ └── kustomization.yaml │ ├── update_merge_fallback │ │ ├── initial │ │ │ ├── kustomization.yaml │ │ │ ├── namespace.yaml │ │ │ └── patch_deployment_env.yaml │ │ └── modified │ │ │ ├── kustomization.yaml │ │ │ ├── namespace.yaml │ │ │ └── patch_deployment_envfrom.yaml │ ├── update_recreate │ │ ├── initial │ │ │ ├── kustomization.yaml │ │ │ └── namespace.yaml │ │ └── modified │ │ │ ├── kustomization.yaml │ │ │ └── patch_selector.yaml │ ├── update_recreate_name_or_namespace_change │ │ ├── initial │ │ │ ├── kustomization.yaml │ │ │ └── namespace.yaml │ │ └── modified │ │ │ └── kustomization.yaml │ ├── update_recreate_roleref │ │ ├── initial │ │ │ ├── kustomization.yaml │ │ │ ├── namespace.yaml │ │ │ └── rbac.yaml │ │ └── modified │ │ │ └── kustomization.yaml │ ├── update_recreate_statefulset │ │ ├── initial │ │ │ ├── kustomization.yaml │ │ │ ├── namespace.yaml │ │ │ └── statefulset.yaml │ │ └── modified │ │ │ └── kustomization.yaml │ ├── update_recreate_storage_class │ │ ├── initial │ │ │ ├── kustomization.yaml │ │ │ ├── storage-class-parameters.yaml │ │ │ └── storage-class-provisioner.yaml │ │ └── modified │ │ │ └── kustomization.yaml │ ├── upgrade_api_version │ │ ├── initial │ │ │ ├── co.yaml │ │ │ ├── crd.yaml │ │ │ ├── kustomization.yaml │ │ │ └── namespace.yaml │ │ └── modified │ │ │ └── kustomization.yaml │ ├── wait-change │ │ └── initial │ │ │ ├── daemonset.yaml │ │ │ ├── kustomization.yaml │ │ │ ├── namespace.yaml │ │ │ └── statefulset.yaml │ ├── wait-fail │ │ └── initial │ │ │ ├── daemonset.yaml │ │ │ ├── kustomization.yaml │ │ │ ├── namespace.yaml │ │ │ └── statefulset.yaml │ ├── wait │ │ ├── initial │ │ │ ├── daemonset.yaml │ │ │ ├── kustomization.yaml │ │ │ ├── namespace.yaml │ │ │ └── statefulset.yaml │ │ └── modified │ │ │ └── kustomization.yaml │ └── webhook │ │ ├── initial │ │ ├── kustomization.yaml │ │ └── webhook.yaml │ │ └── modified │ │ ├── kustomization.yaml │ │ └── webhook-patch.yaml ├── util.go └── util_test.go ├── main.go ├── test-schema-migration._tf ├── test.tf └── tests ├── fakekubeconfig ├── in-cluster.yaml └── kubestack-starter-kind ├── .gitignore ├── Dockerfile ├── README.md ├── kind_zero_cluster.tf ├── kind_zero_providers.tf ├── kind_zero_test_module.tf ├── manifests ├── .gitempty └── extra_configmap.yaml └── versions.tf /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Run Tests 2 | 3 | on: push 4 | 5 | env: 6 | GO_VERSION: ">=1.21" 7 | TERRAFORM_VERSION: "1.4.6" 8 | KIND_VERSION: "v0.17.0" 9 | 10 | jobs: 11 | tf_tests: 12 | runs-on: ${{ matrix.runner }} 13 | strategy: 14 | fail-fast: false 15 | matrix: 16 | runner: ["ubuntu-latest", "windows-latest", "macos-latest"] 17 | 18 | steps: 19 | - name: Checkout using linefeed for tests 20 | run: | 21 | git config --global core.autocrlf false 22 | 23 | - name: 'Checkout' 24 | uses: actions/checkout@v3 25 | 26 | - name: 'Setup K8s' 27 | if: startsWith(matrix.runner, 'ubuntu-') 28 | uses: helm/kind-action@v1.7.0 29 | with: 30 | version: "${{ env.KIND_VERSION }}" 31 | cluster_name: ci 32 | 33 | - name: Set up Go 34 | uses: actions/setup-go@v4 35 | with: 36 | go-version: "${{ env.GO_VERSION }}" 37 | 38 | - name: Set up Helm 39 | uses: azure/setup-helm@v3.5 40 | with: 41 | version: '3.12.0' 42 | 43 | - name: 'Run TF acceptance tests (${{ matrix.runner }})' 44 | if: startsWith(matrix.runner, 'ubuntu-') 45 | env: 46 | KUBECONFIG_PATH: ~/.kube/config 47 | run: make test 48 | 49 | - name: 'Run TF unit tests (${{ matrix.runner }})' 50 | if: startsWith(matrix.runner, 'ubuntu-') == false 51 | env: 52 | KUBECONFIG_PATH: ${{ github.workspace }}/tests/fakekubeconfig 53 | run: | 54 | go test -ldflags "-X google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=ignore" -v ./kustomize 55 | 56 | compile_provider: 57 | runs-on: ubuntu-latest 58 | 59 | steps: 60 | - name: 'Checkout' 61 | uses: actions/checkout@v3 62 | 63 | - name: Set up Go 64 | uses: actions/setup-go@v4 65 | with: 66 | go-version: "${{ env.GO_VERSION }}" 67 | 68 | - name: Run goreleaser build 69 | if: startsWith(github.ref, 'refs/tags/v') 70 | uses: kbst/goreleaser-action@v4 71 | with: 72 | version: latest 73 | args: build --config .goreleaser-build.yml --clean 74 | 75 | - name: Run goreleaser build --snapshot 76 | if: startsWith(github.ref, 'refs/tags/v') == false 77 | uses: kbst/goreleaser-action@v4 78 | with: 79 | version: latest 80 | args: build --config .goreleaser-build.yml --clean --snapshot 81 | 82 | - name: 'Prepare terraform-plugins' 83 | run: | 84 | mkdir -p ./dist/terraform.d/plugins/registry.terraform.io/kbst/kustomization/1.0.0/linux_amd64 85 | cp ./dist/terraform-provider-kustomization_linux_amd64_v1/terraform-provider-kustomization_v* ./dist/terraform.d/plugins/registry.terraform.io/kbst/kustomization/1.0.0/linux_amd64/terraform-provider-kustomization_v1.0.0 86 | 87 | - name: 'Upload terraform-plugins' 88 | uses: actions/upload-artifact@v4 89 | with: 90 | name: terraform-plugins 91 | path: dist/terraform.d/plugins 92 | 93 | int_test_kubeconfig_path: 94 | runs-on: ubuntu-latest 95 | needs: [compile_provider] 96 | 97 | env: 98 | KUBECONFIG_PATH: ~/.kube/config 99 | 100 | steps: 101 | - name: 'Checkout' 102 | uses: actions/checkout@v3 103 | 104 | - name: Setup Terraform 105 | uses: hashicorp/setup-terraform@v2 106 | with: 107 | terraform_wrapper: false 108 | terraform_version: "${{ env.TERRAFORM_VERSION }}" 109 | 110 | - name: 'Download terraform-plugins' 111 | uses: actions/download-artifact@v4 112 | with: 113 | name: terraform-plugins 114 | path: terraform.d/plugins 115 | 116 | - name: 'Ensure provider is executable' 117 | run: chmod +x terraform.d/plugins/registry.terraform.io/kbst/kustomization/1.0.0/linux_amd64/terraform-provider-kustomization_v1.0.0 118 | 119 | - name: 'Setup K8s' 120 | uses: helm/kind-action@v1.7.0 121 | with: 122 | version: "${{ env.KIND_VERSION }}" 123 | cluster_name: ci 124 | 125 | - name: 'Terraform Init' 126 | run: terraform init 127 | 128 | - name: 'Terraform Apply' 129 | run: terraform apply --auto-approve 130 | 131 | int_test_kubeconfig_raw: 132 | runs-on: ubuntu-latest 133 | needs: [compile_provider] 134 | 135 | steps: 136 | - name: 'Checkout' 137 | uses: actions/checkout@v3 138 | 139 | - name: 'Setup K8s' 140 | uses: helm/kind-action@v1.7.0 141 | with: 142 | version: "${{ env.KIND_VERSION }}" 143 | cluster_name: ci 144 | 145 | - name: Setup Terraform 146 | uses: hashicorp/setup-terraform@v2 147 | with: 148 | terraform_wrapper: false 149 | terraform_version: "${{ env.TERRAFORM_VERSION }}" 150 | 151 | - name: 'Download terraform-plugins' 152 | uses: actions/download-artifact@v4 153 | with: 154 | name: terraform-plugins 155 | path: terraform.d/plugins 156 | 157 | - name: 'Ensure provider is executable' 158 | run: chmod +x terraform.d/plugins/registry.terraform.io/kbst/kustomization/1.0.0/linux_amd64/terraform-provider-kustomization_v1.0.0 159 | 160 | - name: 'Create provider.tf with kubeconfig_raw' 161 | run: | 162 | echo "provider "kustomization" {" > provider.tf 163 | echo " kubeconfig_raw = <> provider.tf 164 | kind get kubeconfig --name ci >> provider.tf 165 | echo "EOT" >> provider.tf 166 | echo "}" >> provider.tf 167 | 168 | - name: 'Terraform Init' 169 | run: terraform init 170 | 171 | - name: 'Terraform Apply' 172 | run: terraform apply --auto-approve 173 | 174 | int_test_in_cluster: 175 | runs-on: ubuntu-latest 176 | needs: [compile_provider] 177 | 178 | steps: 179 | - name: 'Checkout' 180 | uses: actions/checkout@v3 181 | 182 | - name: 'Setup K8s' 183 | uses: helm/kind-action@v1.7.0 184 | with: 185 | version: "${{ env.KIND_VERSION }}" 186 | cluster_name: ci 187 | 188 | - name: 'Download terraform-plugins' 189 | uses: actions/download-artifact@v4 190 | with: 191 | name: terraform-plugins 192 | path: terraform.d/plugins 193 | 194 | - name: Create terraform pod 195 | run: kubectl apply -f tests/in-cluster.yaml 196 | 197 | - name: Wait for pod to be ready 198 | run: kubectl wait pod/terraform --for condition=Ready --timeout 60s 199 | 200 | - name: 'Ensure provider is executable' 201 | run: chmod +x terraform.d/plugins/registry.terraform.io/kbst/kustomization/1.0.0/linux_amd64/terraform-provider-kustomization_v1.0.0 202 | 203 | - name: Make provider directory 204 | run: kubectl exec terraform -- mkdir terraform.d 205 | 206 | - name: Copy provider 207 | run: kubectl cp terraform.d/plugins terraform:terraform.d/plugins 208 | 209 | - name: Copy test file 210 | run: kubectl cp test.tf terraform:test.tf 211 | 212 | - name: Copy kustomize directory 213 | run: kubectl cp kustomize terraform:kustomize 214 | 215 | - name: Create provider file 216 | run: kubectl exec -it terraform -- sh -c 'echo "provider \"kustomization\" {" > provider.tf; echo " kubeconfig_incluster = true" >> provider.tf; echo "}" >> provider.tf' 217 | 218 | - name: 'Terraform Init' 219 | run: kubectl exec -it terraform -- terraform init 220 | 221 | - name: 'Terraform Apply' 222 | run: kubectl exec -it terraform -- terraform apply --auto-approve 223 | 224 | int_test_state_import: 225 | runs-on: ubuntu-latest 226 | needs: [compile_provider] 227 | 228 | env: 229 | KUBECONFIG_PATH: ~/.kube/config 230 | 231 | steps: 232 | - name: 'Checkout' 233 | uses: actions/checkout@v3 234 | 235 | - name: 'Setup K8s' 236 | uses: helm/kind-action@v1.7.0 237 | with: 238 | version: "${{ env.KIND_VERSION }}" 239 | cluster_name: ci 240 | 241 | - name: Setup Terraform 242 | uses: hashicorp/setup-terraform@v2 243 | with: 244 | terraform_wrapper: false 245 | terraform_version: "${{ env.TERRAFORM_VERSION }}" 246 | 247 | - name: 'Download terraform-plugins' 248 | uses: actions/download-artifact@v4 249 | with: 250 | name: terraform-plugins 251 | path: terraform.d/plugins 252 | 253 | - name: 'Ensure provider is executable' 254 | run: chmod +x terraform.d/plugins/registry.terraform.io/kbst/kustomization/1.0.0/linux_amd64/terraform-provider-kustomization_v1.0.0 255 | 256 | - name: 'Download kustomize' 257 | run: | 258 | wget https://github.com/kubernetes-sigs/kustomize/releases/download/kustomize%2Fv3.5.4/kustomize_v3.5.4_linux_amd64.tar.gz 259 | sudo tar -C /usr/local/bin -xvf kustomize_v3.5.4_linux_amd64.tar.gz 260 | kustomize version 261 | 262 | - name: 'Kubectl apply' 263 | run: | 264 | kustomize build kustomize/test_kustomizations/basic/initial | kubectl apply -f - 265 | 266 | - name: 'Terraform Init' 267 | run: terraform init 268 | 269 | - name: 'Terraform Import' 270 | run: | 271 | terraform import 'kustomization_resource.from_build["_/Namespace/_/test-basic"]' _/Namespace/_/test-basic 272 | terraform import 'kustomization_resource.from_build["apps/Deployment/test-basic/test"]' apps/Deployment/test-basic/test 273 | terraform import 'kustomization_resource.from_build["_/Service/test-basic/test"]' _/Service/test-basic/test 274 | terraform import 'kustomization_resource.from_build["networking.k8s.io/Ingress/test-basic/test"]' networking.k8s.io/Ingress/test-basic/test 275 | 276 | - name: 'Terraform Apply' 277 | run: terraform apply --auto-approve 278 | 279 | int_test_state_migration: 280 | runs-on: ubuntu-latest 281 | needs: [compile_provider] 282 | 283 | env: 284 | KUBECONFIG_PATH: ~/.kube/config 285 | 286 | steps: 287 | - name: 'Checkout' 288 | uses: actions/checkout@v3 289 | 290 | - name: 'Setup K8s' 291 | uses: helm/kind-action@v1.7.0 292 | with: 293 | version: "${{ env.KIND_VERSION }}" 294 | cluster_name: ci 295 | 296 | - name: Setup Terraform 297 | uses: hashicorp/setup-terraform@v2 298 | with: 299 | terraform_wrapper: false 300 | terraform_version: "${{ env.TERRAFORM_VERSION }}" 301 | 302 | - name: 'Temporarily use old provider version' 303 | run: | 304 | mv test-schema-migration._tf test.tf 305 | 306 | - name: 'Terraform Init' 307 | run: terraform init 308 | 309 | - name: 'Terraform Apply' 310 | run: terraform apply --auto-approve 311 | 312 | - name: 'Download terraform-plugins' 313 | uses: actions/download-artifact@v4 314 | with: 315 | name: terraform-plugins 316 | path: terraform.d/plugins 317 | 318 | - name: 'Ensure provider is executable' 319 | run: chmod +x terraform.d/plugins/registry.terraform.io/kbst/kustomization/1.0.0/linux_amd64/terraform-provider-kustomization_v1.0.0 320 | 321 | - name: 'Reset provider version' 322 | run: | 323 | git checkout -- test.tf 324 | 325 | - name: 'Terraform Init' 326 | run: terraform init --upgrade 327 | 328 | - name: 'Terraform Apply' 329 | run: terraform apply --auto-approve 330 | 331 | int_test_kubestack_kind: 332 | runs-on: ubuntu-latest 333 | needs: [compile_provider] 334 | 335 | steps: 336 | - name: 'Checkout' 337 | uses: actions/checkout@v3 338 | 339 | - name: 'Download terraform-plugins' 340 | uses: actions/download-artifact@v4 341 | with: 342 | name: terraform-plugins 343 | path: tests/kubestack-starter-kind/terraform.d/plugins 344 | 345 | - name: 'Ensure provider is executable' 346 | run: chmod +x tests/kubestack-starter-kind/terraform.d/plugins/registry.terraform.io/kbst/kustomization/1.0.0/linux_amd64/terraform-provider-kustomization_v1.0.0 347 | 348 | - name: 'Build Kubestack Image' 349 | run: | 350 | docker build \ 351 | -t test-image:${{ github.sha }} \ 352 | tests/kubestack-starter-kind/ 353 | 354 | - name: 'Terraform Init' 355 | run: | 356 | docker run \ 357 | --rm \ 358 | --privileged \ 359 | --net host \ 360 | -v `pwd`/tests/kubestack-starter-kind:/infra \ 361 | -v /var/run/docker.sock:/var/run/docker.sock \ 362 | test-image:${{ github.sha }} \ 363 | terraform init 364 | 365 | - name: 'Terraform Workspace' 366 | run: | 367 | docker run \ 368 | --rm \ 369 | --privileged \ 370 | --net host \ 371 | -v `pwd`/tests/kubestack-starter-kind:/infra \ 372 | -v /var/run/docker.sock:/var/run/docker.sock \ 373 | test-image:${{ github.sha }} \ 374 | terraform workspace new apps 375 | 376 | - name: 'Terraform Apply' 377 | run: | 378 | docker run \ 379 | --rm \ 380 | --privileged \ 381 | --net host \ 382 | -v `pwd`/tests/kubestack-starter-kind:/infra \ 383 | -v /var/run/docker.sock:/var/run/docker.sock \ 384 | test-image:${{ github.sha }} \ 385 | terraform apply --auto-approve 386 | 387 | - name: 'Terraform Destroy' 388 | run: | 389 | docker run \ 390 | --rm \ 391 | --privileged \ 392 | --net host \ 393 | -v `pwd`/tests/kubestack-starter-kind:/infra \ 394 | -v /var/run/docker.sock:/var/run/docker.sock \ 395 | test-image:${{ github.sha }} \ 396 | terraform destroy --auto-approve 397 | 398 | goreleaser: 399 | runs-on: ubuntu-latest 400 | needs: 401 | - tf_tests 402 | - int_test_kubeconfig_path 403 | - int_test_kubeconfig_raw 404 | - int_test_in_cluster 405 | - int_test_state_import 406 | - int_test_kubestack_kind 407 | if: startsWith(github.ref, 'refs/tags/v') 408 | steps: 409 | - name: Checkout 410 | uses: actions/checkout@v2 411 | 412 | - name: Set up Go 413 | uses: actions/setup-go@v4 414 | with: 415 | go-version: "${{ env.GO_VERSION }}" 416 | 417 | - name: Import GPG key 418 | id: import_gpg 419 | uses: kbst/ghaction-import-gpg@v5 420 | with: 421 | gpg_private_key: ${{ secrets.GPG_PRIVATE_KEY }} 422 | passphrase: ${{ secrets.GPG_PASSPHRASE }} 423 | 424 | - name: Run goreleaser release 425 | uses: kbst/goreleaser-action@v4 426 | with: 427 | version: latest 428 | args: release 429 | env: 430 | GPG_FINGERPRINT: ${{ steps.import_gpg.outputs.fingerprint }} 431 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 432 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .terraform* 2 | terraform.d 3 | *.tfstate* 4 | crash.log 5 | dist/ 6 | kustomize/test_kustomizations/helm/remote/ 7 | -------------------------------------------------------------------------------- /.goreleaser-build.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | before: 3 | hooks: 4 | - go mod tidy 5 | builds: 6 | - env: 7 | - CGO_ENABLED=0 8 | mod_timestamp: '{{ .CommitTimestamp }}' 9 | flags: 10 | - -trimpath 11 | ldflags: 12 | - '-s -w -X main.version={{.Version}} -X main.commit={{.Commit}}' 13 | - '-X google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn' 14 | goos: 15 | - linux 16 | goarch: 17 | - amd64 18 | binary: '{{ .ProjectName }}_v{{ .Version }}' 19 | -------------------------------------------------------------------------------- /.goreleaser.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | before: 3 | hooks: 4 | - go mod tidy 5 | builds: 6 | - env: 7 | - CGO_ENABLED=0 8 | mod_timestamp: '{{ .CommitTimestamp }}' 9 | flags: 10 | - -trimpath 11 | ldflags: 12 | - '-s -w -X main.version={{.Version}} -X main.commit={{.Commit}}' 13 | - '-X google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn' 14 | goos: 15 | - freebsd 16 | - windows 17 | - linux 18 | - darwin 19 | goarch: 20 | - amd64 21 | - '386' 22 | - arm 23 | - arm64 24 | ignore: 25 | - goos: darwin 26 | goarch: '386' 27 | binary: '{{ .ProjectName }}_v{{ .Version }}' 28 | archives: 29 | - format: zip 30 | # artifact need to match the repository name, 31 | # while the binary name needs to match the provider name 32 | # this is due to an unfortunate mistake I made when I named the provider 33 | name_template: '{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}' 34 | checksum: 35 | name_template: '{{ .ProjectName }}_{{ .Version }}_SHA256SUMS' 36 | algorithm: sha256 37 | signs: 38 | - artifacts: checksum 39 | args: 40 | # if you are using this is a GitHub action or some other automated pipeline, you 41 | # need to pass the batch flag to indicate its not interactive. 42 | - "--batch" 43 | - "--local-user" 44 | - "{{ .Env.GPG_FINGERPRINT }}" # set this environment variable for your signing key 45 | - "--output" 46 | - "${signature}" 47 | - "--detach-sign" 48 | - "${artifact}" 49 | release: 50 | draft: true 51 | prerelease: auto 52 | changelog: 53 | disable: false 54 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at hello@kubestack.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Please follow common sense when creating issues and [the GitHub flow](https://guides.github.com/introduction/flow/) after forking when creating merge requests. 4 | 5 | ## Issues 6 | 7 | Issues are very valuable to this project. 8 | 9 | - Ideas are a valuable source of contributions others can make 10 | - Problems show where this project is lacking 11 | - With a question, you show where contributors can improve the user experience 12 | 13 | Thank you for creating them. 14 | 15 | ## Merge Requests 16 | 17 | Merge requests are a great way to get your ideas into this repository. 18 | 19 | When deciding if I merge in a merge request I look at the following things: 20 | 21 | ### Does it state intent 22 | 23 | You should be clear about which problem you're trying to solve with your 24 | contribution. 25 | 26 | For example: 27 | 28 | > Add link to code of conduct in README.md 29 | 30 | Doesn't tell me anything about why you're doing that 31 | 32 | > Add link to code of conduct in README.md because users don't always look in the CONTRIBUTING.md 33 | 34 | Tells me the problem that you have found, and the merge request shows me the action you have taken to solve it. 35 | 36 | ### Is it of good quality 37 | 38 | - There are no spelling mistakes 39 | - It reads well 40 | - For English language contributions: Has a good score on [Grammarly](grammarly.com) or [Hemingway Editor](http://www.hemingwayapp.com/) 41 | 42 | ### Does it move this repository closer to my vision for the repository 43 | 44 | The aim of this repository is documented at [README](README.md). 45 | 46 | ### Does it follow the contributor covenant 47 | 48 | This repository has a [code of conduct](./CODE_OF_CONDUCT.md), I will remove things that do not respect it. 49 | 50 | The origin of this document is from [PurpleBooth Templates](https://github.com/PurpleBooth/a-good-readme-template). 51 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | build: 2 | GOOS=linux GOARCH=amd64 go build -ldflags "-X google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn" -o terraform.d/plugins/registry.terraform.io/kbst/kustomization/1.0.0/linux_amd64/terraform-provider-kustomization 3 | GOOS=darwin GOARCH=amd64 go build -ldflags "-X google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn" -o terraform.d/plugins/registry.terraform.io/kbst/kustomization/1.0.0/darwin_amd64/terraform-provider-kustomization 4 | 5 | test: 6 | TF_ACC=1 go test -ldflags "-X google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=ignore" -v ./kustomize 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | Kubestack, The Open Source Gitops Framework 3 |

4 | 5 |

Terraform Provider Kustomize

6 | 7 |
8 | 9 | [![Status](https://img.shields.io/badge/status-active-success.svg)]() 10 | ![Run Tests](https://github.com/kbst/terraform-provider-kustomize/workflows/Run%20Tests/badge.svg?branch=master&event=push) 11 | [![GitHub Issues](https://img.shields.io/github/issues/kbst/terraform-provider-kustomization.svg)](https://github.com/kbst/terraform-provider-kustomization/issues) 12 | [![GitHub Pull Requests](https://img.shields.io/github/issues-pr/kbst/terraform-provider-kustomization.svg)](https://github.com/kbst/terraform-provider-kustomization/pulls) 13 | 14 |
15 | 16 |
17 | 18 | ![GitHub Repo stars](https://img.shields.io/github/stars/kbst/terraform-provider-kustomization?style=social) 19 | ![Twitter Follow](https://img.shields.io/twitter/follow/kubestack?style=social) 20 | 21 |
22 | 23 | 24 |

Join Our Contributors!

25 | 26 |
27 | 28 | 29 | 30 | 31 | 32 |
33 | 34 | ## Introduction 35 | 36 | The Terraform provider for Kustomize is available from the [Terraform registry](https://registry.terraform.io/providers/kbst/kustomization/latest). 37 | 38 | Please refer to the [documentation](https://registry.terraform.io/providers/kbst/kustomization/latest/docs) for information on how to use the `kustomization_build` and `kustomization_overlay` data sources, or the `kustomization_resource` resource. 39 | 40 | This is a standalone Terraform Provider, but is also used in the [Terraform GitOps framework Kubestack](https://www.kubestack.com/). 41 | 42 | 43 | ## Getting Help 44 | 45 | **Community Help** 46 | If you have any questions while following the tutorial, join the [#kubestack](https://app.slack.com/client/T09NY5SBT/CMBCT7XRQ) channel on the Kubernetes community. To create an account request an [invitation](https://slack.k8s.io/). 47 | 48 | **Professional Services** 49 | For organizations interested in accelerating their GitOps journey, [professional services](https://www.kubestack.com/lp/professional-services) are available. 50 | 51 | 52 | ## Contributing 53 | Contributions to the Kubestack framework are welcome and encouraged. Before contributing, please read the [Contributing](./CONTRIBUTING.md) and [Code of Conduct](./CODE_OF_CONDUCT.md) Guidelines. 54 | 55 | One super simple way to contribute to the success of this project is to give it a star. 56 | 57 |
58 | 59 | ![GitHub Repo stars](https://img.shields.io/github/stars/kbst/terraform-provider-kustomization?style=social) 60 | 61 |
62 | 63 | 64 | ## Development Requirements 65 | 66 | - [Terraform](https://www.terraform.io/downloads.html) 0.12.x 67 | - [Go](https://golang.org/doc/install) 1.13 (to build the provider plugin) 68 | 69 | 70 | ## Building and Developing the Provider 71 | 72 | To work on the provider, you need go installed on your machine. The provider uses go mod to manage its dependencies, so GOPATH is not required. 73 | 74 | To compile the provider, run `make build` as shown below. This will build the provider and put the provider binary in the `terraform.d/plugins/linux_amd64/` directory. 75 | 76 | ```sh 77 | make build 78 | ``` 79 | 80 | In order to test the provider, run the acceptance tests using `make test`. You have to set the `KUBECONFIG_PATH` environment variable to point the tests to a valid config file. Each tests uses an individual namespaces. [Kind](https://github.com/kubernetes-sigs/kind) or [Minikube](https://github.com/kubernetes/minikube) clusters work well for testing. 81 | 82 | ```sh 83 | make test 84 | ``` 85 | 86 | ### Running the provider under debug 87 | 88 | Running in debug mode is a four step process - launch the plugin in debug mode under delve, connect your IDE to delve, connect terraform to the plugin, and 89 | then run terraform. Instructions here are for Visual Studio Code, configuring other IDEs is likely to be a similar process 90 | 91 | * Ensure you have [`delve` installed](https://github.com/go-delve/delve/tree/master/Documentation/installation) 92 | * Build the plugin locally using `go build ./...` 93 | * From the terraform repository you wish to debug, run the following 94 | ``` 95 | 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 96 | ``` 97 | If you run this outside of the terraform repository (e.g. in the plugin source directory), kustomize gets very confused when trying to find files 98 | * In Visual Studio Code, add the [following configuration to launch.json](https://code.visualstudio.com/docs/editor/debugging#_launch-configurations) 99 | ``` 100 | { 101 | "name": "Connect to server", 102 | "type": "go", 103 | "request": "attach", 104 | "mode": "remote", 105 | "remotePath": "${workspaceFolder}", 106 | "port": 49188, 107 | "host": "127.0.0.1", 108 | "apiVersion": 2, 109 | "env": { 110 | "KUBECONFIG_PATH": "${HOME}/.kube/config" 111 | }, 112 | "dlvLoadConfig": { 113 | "followPointers": true, 114 | "maxVariableRecurse": 1, 115 | "maxStringLen": 512, 116 | "maxArrayValues": 64, 117 | "maxStructFields": -1 118 | } 119 | } 120 | ``` 121 | * Click the debug button and start `Connect to server`. 122 | * From the terminal you started `dlv` from, you will see something like: 123 | ``` 124 | Provider server started; to attach Terraform, set TF_REATTACH_PROVIDERS to the following: 125 | {"registry.terraform.io/kbst/kustomization":{"Protocol":"grpc","Pid":13366,"Test":true,"Addr":{"Network":"unix","String":"/var/folders/7c/wdp684z11w1_6cj0d6lgl8hw0000gn/T/plugin2650218557"}}} 126 | ``` 127 | Set this value using export `TF_REATTACH_PROVIDERS={"registry...}}}` in the terminal you want to run terraform from 128 | * Set any breakpoints you wish to use 129 | * Run terraform 130 | 131 | 132 | ### Running a specific test in debug mode 133 | 134 | * Add the following configuration to .vscode/launch.json, updating the `TestFunctionNameGoesHere` 135 | to the name of the function you want to test: 136 | 137 | ``` 138 | { 139 | "name": "Launch test function", 140 | "type": "go", 141 | "request": "launch", 142 | "mode": "test", 143 | "program": "${workspaceFolder}/kustomize", 144 | "env": { 145 | "TF_ACC": "1", 146 | "KUBECONFIG_PATH": "${env:HOME}/.kube/config" 147 | }, 148 | "args": [ 149 | "-test.v", 150 | "-test.run", 151 | "^TestFunctionNameGoesHere$", 152 | ], 153 | } 154 | ``` 155 | * Set any breakpoints you want to set 156 | * Click the debug button and choose "Launch test function" in the dropdown 157 | 158 | ## Kubestack Repositories 159 | * [kbst/terraform-kubestack](https://github.com/kbst/terraform-kubestack) 160 | * Terraform GitOps Framework - Everything you need to build reliable automation for AKS, EKS and GKE Kubernetes clusters in one free and open-source framework. 161 | * [kbst/kbst](https://github.com/kbst/kbst) 162 | * Kubestack Framework CLI - All-in-one CLI to scaffold your Infrastructure as Code repository and deploy your entire platform stack locally for faster iteration. 163 | * [kbst/terraform-provider-kustomization](https://github.com/kbst/terraform-provider-kustomization) (this repository) 164 | * Kustomize Terraform Provider - A Kubestack maintained Terraform provider for Kustomize, available in the [Terraform registry](https://registry.terraform.io/providers/kbst/kustomization/latest). 165 | * [kbst/catalog](https://github.com/kbst/catalog) 166 | * Catalog of cluster services as Kustomize bases - Continuously tested and updated Kubernetes services, installed and customizable using native Terraform syntax. 167 | 168 | -------------------------------------------------------------------------------- /assets/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kbst/terraform-provider-kustomization/adf37d2cbfc6f5fc6f3bff008397b98939ab3915/assets/favicon.png -------------------------------------------------------------------------------- /docs/data-sources/build.md: -------------------------------------------------------------------------------- 1 | # `kustomization_build` Data Source 2 | 3 | Data source to `kustomize build` a Kustomization and return a set of `ids` and hash map of `manifests` by `id`. 4 | 5 | -> This data source was previously named `kustomization`. The name has been changed to follow the Terraform conventions. The previous name is still supported. 6 | 7 | ## Example Usage 8 | 9 | ```hcl 10 | data "kustomization_build" "test" { 11 | path = "test_kustomizations/basic/initial" 12 | kustomize_options { 13 | load_restrictor = "none" 14 | enable_helm = true 15 | helm_path = "/path/to/helm" 16 | } 17 | } 18 | 19 | ``` 20 | 21 | ## Argument Reference 22 | 23 | - `path` - (Required) Path to a kustomization directory. 24 | 25 | ### `kustomize_options` - (optional) 26 | 27 | #### Child attributes 28 | 29 | - `load_restrictor` - setting this to `"none"` disables load restrictions 30 | - `enable_helm` - setting this to `true` allows referencing helm charts in the kustomization.yaml 31 | - `helm_path` - set this to the path of the `helm` binary (defaults to: `helmV3`) 32 | 33 | ## Attribute Reference 34 | 35 | - `ids` - Set of Kustomize resource IDs. 36 | - `ids_prio` - List of Kustomize resource IDs grouped into three sets. 37 | - `ids_prio[0]`: `Kind: Namespace` and `Kind: CustomResourceDefinition` 38 | - `ids_prio[1]`: All `Kind`s not in `ids_prio[0]` or `ids_prio[2]` 39 | - `ids_prio[2]`: `Kind: MutatingWebhookConfiguration` and `Kind: ValidatingWebhookConfiguration` 40 | - `manifests` - Map of JSON encoded Kubernetes resource manifests by ID. 41 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | # Kustomize Provider 2 | 3 | This provider allows building existing kustomizations using the `kustomization_build` data source or defining 4 | dynamic kustomizations in HCL using the `kustomization_overlay` data source and applying the resources from 5 | either kustomization against a Kubernetes cluster using the `kustomization_resource` resource. 6 | 7 | The provider is maintained as part of the [Terraform GitOps framework Kubestack](https://www.kubestack.com/). 8 | 9 | Using this Kustomize provider and Terraform has three main benefits compared to applying a kustomization using `kubectl`: 10 | 11 | 1. Running `terraform plan` will show a diff of the changes to be applied. 12 | 1. Deleted resources from a previous configuration will be purged. 13 | 1. Changes to immutable fields will generate a destroy and re-create plan. 14 | 15 | As such the provider can be useful to replace kustomize/kubectl integrated into a Terraform configuration as a provisioner or to replace standalone `kubectl diff/apply` steps in CI/CD. 16 | 17 | ## Example Usage 18 | 19 | ```hcl 20 | terraform { 21 | required_providers { 22 | kustomization = { 23 | source = "kbst/kustomization" 24 | version = "0.9.0" 25 | } 26 | } 27 | } 28 | 29 | provider "kustomization" { 30 | # one of kubeconfig_path, kubeconfig_raw or kubeconfig_incluster must be set 31 | 32 | # kubeconfig_path = "~/.kube/config" 33 | # can also be set using KUBECONFIG_PATH environment variable 34 | 35 | # kubeconfig_raw = data.template_file.kubeconfig.rendered 36 | # kubeconfig_raw = yamlencode(local.kubeconfig) 37 | 38 | # kubeconfig_incluster = true 39 | } 40 | 41 | ``` 42 | 43 | ## Argument Reference 44 | 45 | - `kubeconfig_path` - Path to a kubeconfig file. Can be set using `KUBECONFIG_PATH` environment variable. 46 | - `kubeconfig_raw` - Raw kubeconfig file. If `kubeconfig_raw` is set, `kubeconfig_path` is ignored. 47 | - `kubeconfig_incluster` - Set to `true` when running inside a kubernetes cluster. 48 | - `context` - (Optional) Context to use in kubeconfig with multiple contexts, if not specified the default context is used. 49 | - `legacy_id_format` - (Optional) Defaults to `false`. Provided for backward compability, set to `true` to use the legacy ID format. Removed starting `0.9.0`. 50 | - `gzip_last_applied_config` - (Optional) Defaults to `true`. Use a gzip compressed and base64 encoded value for the lastAppliedConfig annotation if a resource would otherwise exceed the Kubernetes max annotation size. All other resources use the regular uncompressed annotation. Set to `false` to never use the compressed annotation. 51 | 52 | ## Migrating resource IDs from legacy format to format enabling API version upgrades 53 | 54 | -> Support for the legacy ID format has been removed in version `0.9.0`. The provider has defaulted to the new format since version `0.7.0`. If you have been using the legacy format with the `legacy_id_format = true` backwards compatibility until now, make sure to migrate IDs before upgrading to `0.9.0`. 55 | 56 | To allow the kustomization provider to manage API version upgrades, the version has been removed from resource IDs. 57 | As this is a breaking change, we provide a helper script to move resources in the state. 58 | If you choose not to move resources in the state, a destroy and recreate of all resources managed by the provider will be required. 59 | We are also taking this as an opportunity, to refactor the ID format. 60 | 61 | * Legacy format: `apps_v1_Deployment|test-ns|test-deploy` or `~G_v1_Service|test-ns|test-svc` 62 | * New format: `apps/Deployment/test-ns/test-deploy` or `_/Service/test-ns/test-svc` 63 | 64 | The general form is `group/Kind/namespace/name` with `_` as a placeholder for empty values (e.g. `_/Namespace/_/test-namespace`). 65 | 66 | The commands below will create a file `state_mv.sh` with one `terraform state mv` command per resource. 67 | 68 | ```shell 69 | cat > migrate.py <<'EOF' 70 | import sys 71 | import re 72 | 73 | for si in sys.stdin.readlines(): 74 | 75 | if not "kustomization_resource" in si: 76 | continue 77 | 78 | so = re.sub(r"(.*)\[\"([^_]*)\_[^_]*\_([^|]*)\|([^|]*)\|([^\"]*)\"\]", 79 | r'\1["\2/\3/\4/\5"]', si) 80 | 81 | so = re.sub(r"\~[GX]", r"_", so) 82 | 83 | print(f"terraform state mv '{si.strip()}' '{so.strip()}'") 84 | 85 | EOF 86 | 87 | terraform state list | python3 migrate.py > state_mv.sh 88 | ``` 89 | 90 | After carefully inspecting the generated commands in `state_mv.sh`, you can execute them using: 91 | 92 | ```shell 93 | bash state_mv.sh 94 | ``` 95 | 96 | ## Imports 97 | 98 | To import existing resources, run `terraform import` as shown below. 99 | Resources to be imported require a valid `kubectl.kubernetes.io/last-applied-configuration` annotation. 100 | 101 | ``` 102 | terraform import 'kustomization_resource.test["apps/Deployment/test-namespace/test-deployment"]' apps/Deployment/test-namespace/test-deployment 103 | ``` 104 | -------------------------------------------------------------------------------- /docs/resources/resource.md: -------------------------------------------------------------------------------- 1 | # `kustomization_resource` Resource 2 | 3 | Resource to provision JSON encoded Kubernetes manifests as produced by the `kustomization_build` or `kustomization_overlay` data sources on a Kubernetes cluster. Uses client-go dynamic client and server side dry runs to determine the Terraform plan for changing a resource. 4 | 5 | ### Terraform Limitation 6 | 7 | Terraform providers can not control the Terraform dependency graph. But namespaced Kubernetes resources require the namespace to be created first. And there are other examples, like CRDs. To work around Terraform's limitation, this provider retries creating Kubernetes resources that depend on another Kubernetes resource. This works well in many cases but has a potential race condition. It is possible, for various reasons, that the resource's dependency does not get created within the number of retries. Terraform will continue with other resources, but not retry the already failed ones. Applying the failed resources, requires a second Terraform run. 8 | 9 | One possible workaround is to increase the number of parallel resource operations, using Terraform's `-parallelism=n` parameter. This increases the chance, that the resource the provider is waiting for gets created in time. But increased parallelism is not always an option. 10 | 11 | A better approach is to instruct Terraform to handle the resources in the correct order, using an explicit `depends_on`. For this reason, both data sources additionally return `ids_prio`, three sets of IDs grouped by the order they should be applied in. 12 | 13 | In addition to the inability of a provider to control the Terraform dependency graph, marking an attribute sensitive, to hide it from the Terraform plan output, is not possible conditionally in the provider. As a result, the `manifest` attribute can't be marked sensitive for Kubernetes secrets, but kept non-sensitive for all other resources to keep the ability to preview changes. As a result, marking the `manifest` attribute sensitive for Kubernetes secrets, and potentially other resources, has to be handled conditionally in Terraform code. 14 | 15 | The explicit `depends_on` for correct ordering of resources, and the conditional `sensitive` to prevent leaking secret values to the Terraform plan output make using the provider rather verbose. To make this easier to use, a convenience module is available, which handles all this inside the module and allows setting the Kustomizations as module variables, that are then passed to the `kustomization_overlay` data source. 16 | 17 | Below are two examples, one using the convenience module, and another one showing the explicit `depends_on` and `for_each`, as well as the conditional `sensitive`. 18 | 19 | ## Example Usage 20 | 21 | ### Module Example 22 | 23 | ```hcl 24 | module "example_custom_manifests" { 25 | source = "kbst.xyz/catalog/custom-manifests/kustomization" 26 | version = "0.3.0" 27 | 28 | configuration_base_key = "default" # must match workspace name 29 | configuration = { 30 | default = { 31 | namespace = "example-${terraform.workspace}" 32 | 33 | resources = [ 34 | "${path.root}/manifests/example/namespace.yaml", 35 | "${path.root}/manifests/example/deployment.yaml", 36 | "${path.root}/manifests/example/service.yaml" 37 | ] 38 | 39 | common_labels = { 40 | "env" = terraform.workspace 41 | } 42 | } 43 | } 44 | } 45 | ``` 46 | 47 | Complete documentation of the custom-manifests convenience module can be found in the [Kubestack framework documentation](https://www.kubestack.com/framework/documentation/cluster-service-modules#custom-manifests). 48 | 49 | ### Provider Example 50 | 51 | Usage of the provider requires one of the data sources, which return IDs and manifests as JSON strings, and the `kustomization_resource` to loop over the IDs using `for_each`, explicit `depends_on` as well as conditional `sensitive` on the `manifest` attribute. 52 | 53 | ```hcl 54 | data "kustomization_build" "test" { 55 | path = "kustomize/test_kustomizations/basic/initial" 56 | } 57 | 58 | # first loop through resources in ids_prio[0] 59 | resource "kustomization_resource" "p0" { 60 | for_each = data.kustomization_build.test.ids_prio[0] 61 | 62 | manifest = ( 63 | contains(["_/Secret"], regex("(?P.*/.*)/.*/.*", each.value)["group_kind"]) 64 | ? sensitive(data.kustomization_build.test.manifests[each.value]) 65 | : data.kustomization_build.test.manifests[each.value] 66 | ) 67 | } 68 | 69 | # then loop through resources in ids_prio[1] 70 | # and set an explicit depends_on on kustomization_resource.p0 71 | # wait 2 minutes for any deployment, statefulset or daemonset to become ready 72 | resource "kustomization_resource" "p1" { 73 | for_each = data.kustomization_build.test.ids_prio[1] 74 | 75 | manifest = ( 76 | contains(["_/Secret"], regex("(?P.*/.*)/.*/.*", each.value)["group_kind"]) 77 | ? sensitive(data.kustomization_build.test.manifests[each.value]) 78 | : data.kustomization_build.test.manifests[each.value] 79 | ) 80 | wait = true 81 | timeouts { 82 | create = "2m" 83 | update = "2m" 84 | } 85 | 86 | depends_on = [kustomization_resource.p0] 87 | } 88 | 89 | # finally, loop through resources in ids_prio[2] 90 | # and set an explicit depends_on on kustomization_resource.p1 91 | resource "kustomization_resource" "p2" { 92 | for_each = data.kustomization_build.test.ids_prio[2] 93 | 94 | manifest = ( 95 | contains(["_/Secret"], regex("(?P.*/.*)/.*/.*", each.value)["group_kind"]) 96 | ? sensitive(data.kustomization_build.test.manifests[each.value]) 97 | : data.kustomization_build.test.manifests[each.value] 98 | ) 99 | 100 | depends_on = [kustomization_resource.p1] 101 | } 102 | 103 | ``` 104 | 105 | ## Argument Reference 106 | 107 | - `manifest` - (Required) JSON encoded Kubernetes resource manifest. 108 | - `wait` - Whether to wait for pods to become ready (default false). Currently only has an effect for Deployments, StatefulSets and DaemonSets. 109 | - 'timeouts' - (Optional) Overwrite `create`, `update` or `delete` timeout defaults. Defaults are 5 minutes for `create` and `update` and 10 minutes for `delete`. 110 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/kbst/terraform-provider-kustomize 2 | 3 | go 1.21 4 | 5 | require ( 6 | github.com/hashicorp/terraform-plugin-sdk/v2 v2.32.0 7 | github.com/mitchellh/go-homedir v1.1.0 8 | github.com/stretchr/testify v1.8.4 9 | k8s.io/api v0.29.2 10 | k8s.io/apimachinery v0.29.2 11 | k8s.io/client-go v0.29.2 12 | k8s.io/kubectl v0.29.2 13 | sigs.k8s.io/kustomize/api v0.16.0 14 | sigs.k8s.io/kustomize/kyaml v0.16.0 15 | ) 16 | 17 | require ( 18 | github.com/ProtonMail/go-crypto v0.0.0-20230828082145-3c4c8a2d2371 // indirect 19 | github.com/agext/levenshtein v1.2.3 // indirect 20 | github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect 21 | github.com/cloudflare/circl v1.3.7 // indirect 22 | github.com/davecgh/go-spew v1.1.1 // indirect 23 | github.com/emicklei/go-restful/v3 v3.11.0 // indirect 24 | github.com/evanphx/json-patch v5.6.0+incompatible // indirect 25 | github.com/fatih/color v1.15.0 // indirect 26 | github.com/go-errors/errors v1.4.2 // indirect 27 | github.com/go-logr/logr v1.3.0 // indirect 28 | github.com/go-openapi/jsonpointer v0.19.6 // indirect 29 | github.com/go-openapi/jsonreference v0.20.2 // indirect 30 | github.com/go-openapi/swag v0.22.3 // indirect 31 | github.com/gogo/protobuf v1.3.2 // indirect 32 | github.com/golang/protobuf v1.5.3 // indirect 33 | github.com/google/gnostic-models v0.6.8 // indirect 34 | github.com/google/go-cmp v0.6.0 // indirect 35 | github.com/google/gofuzz v1.2.0 // indirect 36 | github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect 37 | github.com/google/uuid v1.4.0 // indirect 38 | github.com/hashicorp/errwrap v1.1.0 // indirect 39 | github.com/hashicorp/go-checkpoint v0.5.0 // indirect 40 | github.com/hashicorp/go-cleanhttp v0.5.2 // indirect 41 | github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 // indirect 42 | github.com/hashicorp/go-hclog v1.5.0 // indirect 43 | github.com/hashicorp/go-multierror v1.1.1 // indirect 44 | github.com/hashicorp/go-plugin v1.6.0 // indirect 45 | github.com/hashicorp/go-uuid v1.0.3 // indirect 46 | github.com/hashicorp/go-version v1.6.0 // indirect 47 | github.com/hashicorp/hc-install v0.6.2 // indirect 48 | github.com/hashicorp/hcl/v2 v2.19.1 // indirect 49 | github.com/hashicorp/logutils v1.0.0 // indirect 50 | github.com/hashicorp/terraform-exec v0.20.0 // indirect 51 | github.com/hashicorp/terraform-json v0.21.0 // indirect 52 | github.com/hashicorp/terraform-plugin-go v0.21.0 // indirect 53 | github.com/hashicorp/terraform-plugin-log v0.9.0 // indirect 54 | github.com/hashicorp/terraform-registry-address v0.2.3 // indirect 55 | github.com/hashicorp/terraform-svchost v0.1.1 // indirect 56 | github.com/hashicorp/yamux v0.1.1 // indirect 57 | github.com/imdario/mergo v0.3.16 // indirect 58 | github.com/josharian/intern v1.0.0 // indirect 59 | github.com/json-iterator/go v1.1.12 // indirect 60 | github.com/mailru/easyjson v0.7.7 // indirect 61 | github.com/mattn/go-colorable v0.1.13 // indirect 62 | github.com/mattn/go-isatty v0.0.19 // indirect 63 | github.com/mitchellh/copystructure v1.2.0 // indirect 64 | github.com/mitchellh/go-testing-interface v1.14.1 // indirect 65 | github.com/mitchellh/go-wordwrap v1.0.1 // indirect 66 | github.com/mitchellh/mapstructure v1.5.0 // indirect 67 | github.com/mitchellh/reflectwalk v1.0.2 // indirect 68 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 69 | github.com/modern-go/reflect2 v1.0.2 // indirect 70 | github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 // indirect 71 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect 72 | github.com/oklog/run v1.1.0 // indirect 73 | github.com/pkg/errors v0.9.1 // indirect 74 | github.com/pmezard/go-difflib v1.0.0 // indirect 75 | github.com/spf13/pflag v1.0.5 // indirect 76 | github.com/stretchr/objx v0.5.1 // indirect 77 | github.com/vmihailenco/msgpack v4.0.4+incompatible // indirect 78 | github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect 79 | github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect 80 | github.com/xlab/treeprint v1.2.0 // indirect 81 | github.com/zclconf/go-cty v1.14.2 // indirect 82 | go.starlark.net v0.0.0-20230525235612-a134d8f9ddca // indirect 83 | golang.org/x/crypto v0.18.0 // indirect 84 | golang.org/x/mod v0.14.0 // indirect 85 | golang.org/x/net v0.19.0 // indirect 86 | golang.org/x/oauth2 v0.14.0 // indirect 87 | golang.org/x/sys v0.16.0 // indirect 88 | golang.org/x/term v0.16.0 // indirect 89 | golang.org/x/text v0.14.0 // indirect 90 | golang.org/x/time v0.3.0 // indirect 91 | google.golang.org/appengine v1.6.8 // indirect 92 | google.golang.org/genproto/googleapis/rpc v0.0.0-20231106174013-bbf56f31fb17 // indirect 93 | google.golang.org/grpc v1.61.0 // indirect 94 | google.golang.org/protobuf v1.32.0 // indirect 95 | gopkg.in/evanphx/json-patch.v5 v5.6.0 // indirect 96 | gopkg.in/inf.v0 v0.9.1 // indirect 97 | gopkg.in/yaml.v2 v2.4.0 // indirect 98 | gopkg.in/yaml.v3 v3.0.1 // indirect 99 | k8s.io/klog/v2 v2.110.1 // indirect 100 | k8s.io/kube-openapi v0.0.0-20231010175941-2dd684a91f00 // indirect 101 | k8s.io/utils v0.0.0-20230726121419-3b25d923346b // indirect 102 | sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect 103 | sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect 104 | sigs.k8s.io/yaml v1.4.0 // indirect 105 | ) 106 | -------------------------------------------------------------------------------- /kustomize/data_source_kustomization.go: -------------------------------------------------------------------------------- 1 | package kustomize 2 | 3 | import ( 4 | "crypto/sha512" 5 | "encoding/hex" 6 | "fmt" 7 | "hash/crc32" 8 | "log" 9 | "strconv" 10 | "strings" 11 | 12 | "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" 13 | "sigs.k8s.io/kustomize/api/krusty" 14 | "sigs.k8s.io/kustomize/api/resmap" 15 | "sigs.k8s.io/kustomize/api/types" 16 | "sigs.k8s.io/kustomize/kyaml/filesys" 17 | ) 18 | 19 | func getIDFromResources(rm resmap.ResMap) (s string, err error) { 20 | h := sha512.New() 21 | 22 | yaml, err := rm.AsYaml() 23 | if err != nil { 24 | return "", fmt.Errorf("ResMap AsYaml failed: %s", err) 25 | } 26 | h.Write(yaml) 27 | 28 | s = hex.EncodeToString(h.Sum(nil)) 29 | 30 | return s, nil 31 | } 32 | 33 | func determinePrefix(kr *kManifestId) (p uint32) { 34 | // Default prefix to 5 35 | p = 5 36 | 37 | for _, k := range []string{ 38 | "Namespace", 39 | "CustomResourceDefinition", 40 | } { 41 | if strings.HasPrefix(kr.kind, k) { 42 | p = 1 43 | } 44 | } 45 | 46 | for _, k := range []string{ 47 | "MutatingWebhookConfiguration", 48 | "ValidatingWebhookConfiguration", 49 | } { 50 | if strings.HasPrefix(kr.kind, k) { 51 | p = 9 52 | } 53 | } 54 | 55 | return p 56 | } 57 | 58 | func prefixHash(p uint32, h uint32) int { 59 | s := fmt.Sprintf("%01d%010d", p, h) 60 | s = s[0:9] 61 | 62 | i, e := strconv.ParseInt(s, 10, 32) 63 | if e != nil { 64 | // return unmodified hash 65 | log.Printf("idSetHash: %s", e) 66 | return int(h) 67 | } 68 | 69 | return int(i) 70 | } 71 | 72 | func idSetHash(v interface{}) int { 73 | id := v.(string) 74 | 75 | kr := mustParseProviderId(id) 76 | p := determinePrefix(kr) 77 | h := crc32.ChecksumIEEE([]byte(id)) 78 | 79 | return prefixHash(p, h) 80 | } 81 | 82 | func runKustomizeBuild(fSys filesys.FileSystem, path string, kOpts *schema.ResourceData) (rm resmap.ResMap, err error) { 83 | 84 | opts := getKustomizeOptions(kOpts) 85 | 86 | k := krusty.MakeKustomizer(opts) 87 | 88 | rm, err = k.Run(fSys, path) 89 | if err != nil { 90 | return nil, fmt.Errorf("Kustomizer Run for path '%s' failed: %s", path, err) 91 | } 92 | 93 | return rm, nil 94 | } 95 | 96 | func setGeneratedAttributes(d *schema.ResourceData, rm resmap.ResMap) error { 97 | ids, idsPrio, err := flattenKustomizationIDs(rm) 98 | if err != nil { 99 | return fmt.Errorf("couldn't flatten kustomization IDs: %s", err) 100 | } 101 | d.Set("ids", ids) 102 | d.Set("ids_prio", idsPrio) 103 | 104 | resources, err := flattenKustomizationResources(rm) 105 | if err != nil { 106 | return fmt.Errorf("couldn't flatten resources: %s", err) 107 | } 108 | d.Set("manifests", resources) 109 | 110 | id, err := getIDFromResources(rm) 111 | if err != nil { 112 | return fmt.Errorf("couldn't get ID from resources: %s", err) 113 | } 114 | d.SetId(id) 115 | 116 | return nil 117 | } 118 | 119 | func getKustomizeOptions(d *schema.ResourceData) (opts *krusty.Options) { 120 | 121 | opts = krusty.MakeDefaultOptions() 122 | 123 | kOptsList := d.Get("kustomize_options").([]interface{}) 124 | 125 | if len(kOptsList) == 0 { 126 | return opts 127 | } 128 | 129 | kOpts := kOptsList[0].(map[string]interface{}) 130 | getBoolOpt := func(key string) bool { 131 | return kOpts[key] != nil && kOpts[key].(bool) 132 | } 133 | 134 | enableHelm := getBoolOpt("enable_helm") 135 | enableExec := getBoolOpt("enable_exec") 136 | enableStar := getBoolOpt("enable_star") 137 | 138 | enableAlphaPlugins := getBoolOpt("enable_alpha_plugins") 139 | enableAlphaPlugins = enableAlphaPlugins || enableHelm || enableExec || enableStar 140 | 141 | if enableAlphaPlugins { 142 | opts.PluginConfig = types.EnabledPluginConfig(types.BploUseStaticallyLinked) 143 | } 144 | 145 | if kOpts["load_restrictor"] != nil { 146 | if kOpts["load_restrictor"].(string) == "none" { 147 | opts.LoadRestrictions = types.LoadRestrictionsNone 148 | } 149 | } 150 | 151 | opts.PluginConfig.FnpLoadingOptions.EnableExec = enableExec 152 | opts.PluginConfig.FnpLoadingOptions.EnableStar = enableStar 153 | opts.PluginConfig.HelmConfig.Enabled = enableHelm 154 | 155 | if enableHelm && kOpts["helm_path"] != nil { 156 | opts.PluginConfig.HelmConfig.Command = kOpts["helm_path"].(string) 157 | } 158 | 159 | return opts 160 | } 161 | -------------------------------------------------------------------------------- /kustomize/data_source_kustomization_build.go: -------------------------------------------------------------------------------- 1 | package kustomize 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" 7 | 8 | "sigs.k8s.io/kustomize/kyaml/filesys" 9 | ) 10 | 11 | func dataSourceKustomization() *schema.Resource { 12 | return &schema.Resource{ 13 | Read: kustomizationBuild, 14 | 15 | Schema: map[string]*schema.Schema{ 16 | "path": &schema.Schema{ 17 | Type: schema.TypeString, 18 | Required: true, 19 | }, 20 | "kustomize_options": &schema.Schema{ 21 | Type: schema.TypeList, 22 | Optional: true, 23 | MaxItems: 1, 24 | Elem: &schema.Resource{ 25 | Schema: map[string]*schema.Schema{ 26 | "load_restrictor": { 27 | Type: schema.TypeString, 28 | Optional: true, 29 | }, 30 | "enable_alpha_plugins": { 31 | Type: schema.TypeBool, 32 | Optional: true, 33 | }, 34 | "enable_exec": { 35 | Type: schema.TypeBool, 36 | Optional: true, 37 | }, 38 | "enable_helm": { 39 | Type: schema.TypeBool, 40 | Optional: true, 41 | }, 42 | "enable_star": { 43 | Type: schema.TypeBool, 44 | Optional: true, 45 | }, 46 | "helm_path": { 47 | Type: schema.TypeString, 48 | Optional: true, 49 | }, 50 | }, 51 | }, 52 | }, 53 | "ids": &schema.Schema{ 54 | Type: schema.TypeSet, 55 | Computed: true, 56 | Elem: &schema.Schema{Type: schema.TypeString}, 57 | Set: idSetHash, 58 | }, 59 | "ids_prio": &schema.Schema{ 60 | Type: schema.TypeList, 61 | Computed: true, 62 | Elem: &schema.Schema{ 63 | Type: schema.TypeSet, 64 | Set: idSetHash, 65 | }, 66 | }, 67 | "manifests": &schema.Schema{ 68 | Type: schema.TypeMap, 69 | Computed: true, 70 | Elem: &schema.Schema{Type: schema.TypeString}, 71 | }, 72 | }, 73 | } 74 | } 75 | 76 | func kustomizationBuild(d *schema.ResourceData, m interface{}) error { 77 | path := d.Get("path").(string) 78 | 79 | fSys := filesys.MakeFsOnDisk() 80 | 81 | // mutex as tmp workaround for upstream bug 82 | // https://github.com/kubernetes-sigs/kustomize/issues/3659 83 | mu := m.(*Config).Mutex 84 | mu.Lock() 85 | rm, err := runKustomizeBuild(fSys, path, d) 86 | mu.Unlock() 87 | if err != nil { 88 | return fmt.Errorf("kustomizationBuild: %s", err) 89 | } 90 | 91 | return setGeneratedAttributes(d, rm) 92 | } 93 | -------------------------------------------------------------------------------- /kustomize/data_source_kustomization_build_test.go: -------------------------------------------------------------------------------- 1 | package kustomize 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" 8 | ) 9 | 10 | func TestAccDataSourceKustomization_basic(t *testing.T) { 11 | 12 | resource.Test(t, resource.TestCase{ 13 | //PreCheck: func() { testAccPreCheck(t) }, 14 | Providers: testAccProviders, 15 | Steps: []resource.TestStep{ 16 | { 17 | Config: testAccDataSourceKustomizationConfig_basic("test_kustomizations/basic/initial"), 18 | Check: resource.ComposeAggregateTestCheckFunc( 19 | resource.TestCheckResourceAttrSet("data.kustomization_build.test", "id"), 20 | resource.TestCheckResourceAttrSet("data.kustomization_build.test", "path"), 21 | resource.TestCheckResourceAttr("data.kustomization_build.test", "path", "test_kustomizations/basic/initial"), 22 | resource.TestCheckResourceAttr("data.kustomization_build.test", "ids.#", "4"), 23 | resource.TestCheckResourceAttr("data.kustomization_build.test", "ids_prio.#", "3"), 24 | resource.TestCheckResourceAttr("data.kustomization_build.test", "manifests.%", "4"), 25 | ), 26 | }, 27 | }, 28 | }) 29 | } 30 | 31 | func testAccDataSourceKustomizationConfig_basic(path string) string { 32 | return fmt.Sprintf(` 33 | data "kustomization_build" "test" { 34 | path = "%s" 35 | } 36 | `, path) 37 | } 38 | 39 | func TestAccDataSourceKustomization_legacyName(t *testing.T) { 40 | 41 | resource.Test(t, resource.TestCase{ 42 | //PreCheck: func() { testAccPreCheck(t) }, 43 | Providers: testAccProviders, 44 | Steps: []resource.TestStep{ 45 | { 46 | Config: testAccDataSourceKustomizationConfig_legacyName("test_kustomizations/basic/initial"), 47 | Check: resource.ComposeAggregateTestCheckFunc( 48 | resource.TestCheckResourceAttrSet("data.kustomization.test", "id"), 49 | resource.TestCheckResourceAttrSet("data.kustomization.test", "path"), 50 | resource.TestCheckResourceAttr("data.kustomization.test", "path", "test_kustomizations/basic/initial"), 51 | resource.TestCheckResourceAttr("data.kustomization.test", "ids.#", "4"), 52 | resource.TestCheckResourceAttr("data.kustomization.test", "ids_prio.#", "3"), 53 | resource.TestCheckResourceAttr("data.kustomization.test", "manifests.%", "4"), 54 | ), 55 | }, 56 | }, 57 | }) 58 | } 59 | 60 | func testAccDataSourceKustomizationConfig_legacyName(path string) string { 61 | return fmt.Sprintf(` 62 | data "kustomization" "test" { 63 | path = "%s" 64 | } 65 | `, path) 66 | } 67 | 68 | func TestAccDataSourceKustomization_helmChart(t *testing.T) { 69 | 70 | resource.Test(t, resource.TestCase{ 71 | //PreCheck: func() { testAccPreCheck(t) }, 72 | Providers: testAccProviders, 73 | Steps: []resource.TestStep{ 74 | { 75 | Config: testAccDataSourceKustomizationConfig_helm("test_kustomizations/helm/initial"), 76 | Check: resource.ComposeAggregateTestCheckFunc( 77 | resource.TestCheckResourceAttrSet("data.kustomization_build.test", "id"), 78 | resource.TestCheckResourceAttrSet("data.kustomization_build.test", "path"), 79 | resource.TestCheckResourceAttr("data.kustomization_build.test", "path", "test_kustomizations/helm/initial"), 80 | resource.TestCheckResourceAttr("data.kustomization_build.test", "ids.#", "5"), 81 | resource.TestCheckResourceAttr("data.kustomization_build.test", "ids_prio.#", "3"), 82 | resource.TestCheckResourceAttr("data.kustomization_build.test", "manifests.%", "5"), 83 | resource.TestCheckOutput("service", "{\"apiVersion\":\"v1\",\"kind\":\"Service\",\"metadata\":{\"creationTimestamp\":null,\"labels\":{\"app\":\"nginx\"},\"name\":\"nginx\",\"namespace\":\"test-basic\"},\"spec\":{\"ports\":[{\"name\":\"http\",\"port\":80,\"protocol\":\"TCP\",\"targetPort\":80}],\"selector\":{\"app\":\"nginx\"},\"type\":\"ClusterIP\"},\"status\":{\"loadBalancer\":{}}}"), 84 | resource.TestCheckOutput("deployment", "{\"apiVersion\":\"apps/v1\",\"kind\":\"Deployment\",\"metadata\":{\"creationTimestamp\":null,\"labels\":{\"app\":\"nginx\"},\"name\":\"nginx\",\"namespace\":\"test-basic\"},\"spec\":{\"replicas\":1,\"selector\":{\"matchLabels\":{\"app\":\"nginx\"}},\"strategy\":{},\"template\":{\"metadata\":{\"creationTimestamp\":null,\"labels\":{\"app\":\"nginx\"}},\"spec\":{\"containers\":[{\"image\":\"nginx:6.0.10\",\"name\":\"test-basic\",\"resources\":{}}]}}},\"status\":{}}"), 85 | ), 86 | }, 87 | }, 88 | }) 89 | } 90 | 91 | func testAccDataSourceKustomizationConfig_helm(path string) string { 92 | return fmt.Sprintf(` 93 | data "kustomization_build" "test" { 94 | path = "%s" 95 | 96 | kustomize_options { 97 | enable_helm = true 98 | helm_path = "helm" 99 | } 100 | } 101 | 102 | output "service" { 103 | value = data.kustomization_build.test.manifests["_/Service/test-basic/nginx"] 104 | } 105 | 106 | output "deployment" { 107 | value = data.kustomization_build.test.manifests["apps/Deployment/test-basic/nginx"] 108 | } 109 | `, path) 110 | } 111 | -------------------------------------------------------------------------------- /kustomize/data_source_kustomization_overlay_fs.go: -------------------------------------------------------------------------------- 1 | package kustomize 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | "path/filepath" 7 | 8 | "sigs.k8s.io/kustomize/kyaml/filesys" 9 | ) 10 | 11 | var KFILENAME string = "Kustomization" 12 | 13 | var _ filesys.FileSystem = overlayFileSystem{} 14 | 15 | type overlayFileSystem struct { 16 | fs filesys.FileSystem 17 | kfpReal string 18 | kfpVirt string 19 | } 20 | 21 | // When two kustmization_overlay data sources are defined in the same root module 22 | // the shared file system prevents parallel execution. 23 | // This filesys.FileSystem implementation solves this 24 | // by handling the dynamic Kustomization in a temp directory. 25 | func makeOverlayFS(fs filesys.FileSystem) (ofs filesys.FileSystem, tmp string, err error) { 26 | tmp, err = ioutil.TempDir("", "terraform-provider-kustomization-*") 27 | if err != nil { 28 | return ofs, tmp, err 29 | } 30 | kfpReal := filepath.Join(tmp, KFILENAME) 31 | 32 | cwd, err := os.Getwd() 33 | if err != nil { 34 | return ofs, tmp, err 35 | } 36 | kfpVirt := filepath.Join(cwd, KFILENAME) 37 | 38 | ofs = overlayFileSystem{ 39 | fs: fs, 40 | kfpReal: kfpReal, 41 | kfpVirt: kfpVirt, 42 | } 43 | 44 | return ofs, tmp, err 45 | } 46 | 47 | func (ofs overlayFileSystem) Create(name string) (filesys.File, error) { 48 | return ofs.fs.Create(name) 49 | } 50 | 51 | func (ofs overlayFileSystem) Mkdir(name string) error { 52 | return ofs.fs.Mkdir(name) 53 | } 54 | 55 | func (ofs overlayFileSystem) MkdirAll(name string) error { 56 | return ofs.fs.MkdirAll(name) 57 | } 58 | 59 | func (ofs overlayFileSystem) RemoveAll(name string) error { 60 | return ofs.fs.RemoveAll(name) 61 | } 62 | 63 | func (ofs overlayFileSystem) ReadDir(name string) ([]string, error) { 64 | return ofs.fs.ReadDir(name) 65 | } 66 | 67 | func (ofs overlayFileSystem) Open(name string) (filesys.File, error) { 68 | return ofs.fs.Open(name) 69 | } 70 | 71 | func (ofs overlayFileSystem) CleanedAbs(path string) (filesys.ConfirmedDir, string, error) { 72 | if path == ofs.kfpVirt { 73 | // if the path we're looking for is our virtual Kustomization file 74 | // fake a correct CleanedAbs response 75 | cd, _, err := ofs.fs.CleanedAbs(".") 76 | if err != nil { 77 | return "", "", err 78 | } 79 | return cd, KFILENAME, err 80 | } 81 | 82 | return ofs.fs.CleanedAbs(path) 83 | } 84 | 85 | func (ofs overlayFileSystem) Exists(name string) bool { 86 | ex := ofs.fs.Exists(name) 87 | 88 | if ex == false && name == ofs.kfpVirt { 89 | return ofs.fs.Exists(ofs.kfpReal) 90 | } 91 | 92 | return ex 93 | } 94 | 95 | func (ofs overlayFileSystem) Glob(pattern string) ([]string, error) { 96 | return ofs.fs.Glob(pattern) 97 | } 98 | 99 | func (ofs overlayFileSystem) IsDir(name string) bool { 100 | return ofs.fs.IsDir(name) 101 | } 102 | 103 | func (ofs overlayFileSystem) ReadFile(name string) ([]byte, error) { 104 | if name == ofs.kfpVirt { 105 | return ofs.fs.ReadFile(ofs.kfpReal) 106 | } 107 | 108 | return ofs.fs.ReadFile(name) 109 | } 110 | 111 | func (ofs overlayFileSystem) WriteFile(name string, c []byte) error { 112 | abs, err := filepath.Abs(name) 113 | if err != nil { 114 | return err 115 | } 116 | 117 | if abs == ofs.kfpVirt { 118 | return ofs.fs.WriteFile(ofs.kfpReal, c) 119 | } 120 | 121 | return ofs.fs.WriteFile(name, c) 122 | } 123 | 124 | func (ofs overlayFileSystem) Walk(path string, walkFn filepath.WalkFunc) error { 125 | return ofs.fs.Walk(path, walkFn) 126 | } 127 | -------------------------------------------------------------------------------- /kustomize/data_source_kustomization_overlay_fs_test.go: -------------------------------------------------------------------------------- 1 | package kustomize 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | "path/filepath" 7 | "testing" 8 | 9 | "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" 10 | "github.com/stretchr/testify/assert" 11 | "sigs.k8s.io/kustomize/kyaml/filesys" 12 | ) 13 | 14 | // 15 | // 16 | // Test namespace attr 17 | func TestOverlayFileSystemTwoDataSources(t *testing.T) { 18 | 19 | resource.Test(t, resource.TestCase{ 20 | IsUnitTest: true, 21 | Providers: testAccProviders, 22 | Steps: []resource.TestStep{ 23 | { 24 | Config: testOverlayFileSystemTwoDataSourcesConfig(), 25 | Check: resource.ComposeAggregateTestCheckFunc( 26 | resource.TestCheckOutput("check1", "{\"apiVersion\":\"v1\",\"kind\":\"Namespace\",\"metadata\":{\"name\":\"test-overlay1\"}}"), 27 | resource.TestCheckOutput("check2", "{\"apiVersion\":\"v1\",\"kind\":\"Namespace\",\"metadata\":{\"name\":\"test-overlay2\"}}"), 28 | ), 29 | }, 30 | }, 31 | }) 32 | } 33 | 34 | func testOverlayFileSystemTwoDataSourcesConfig() string { 35 | return ` 36 | data "kustomization_overlay" "test1" { 37 | namespace = "test-overlay1" 38 | 39 | resources = [ 40 | "test_kustomizations/basic/initial", 41 | ] 42 | } 43 | 44 | data "kustomization_overlay" "test2" { 45 | namespace = "test-overlay2" 46 | 47 | resources = [ 48 | "test_kustomizations/basic/initial", 49 | ] 50 | } 51 | 52 | output "check1" { 53 | value = data.kustomization_overlay.test1.manifests["_/Namespace/_/test-overlay1"] 54 | } 55 | 56 | output "check2" { 57 | value = data.kustomization_overlay.test2.manifests["_/Namespace/_/test-overlay2"] 58 | } 59 | 60 | ` 61 | } 62 | 63 | // 64 | // 65 | // Unit tests 66 | func TestOverlayFileSystemCreate(t *testing.T) { 67 | tmp, err := ioutil.TempDir("", "test-terraform-provider-kustomization-*") 68 | defer os.RemoveAll(tmp) 69 | assert.Equal(t, nil, err, nil) 70 | name := filepath.Join(tmp, "test-file") 71 | 72 | dfs := filesys.MakeFsOnDisk() 73 | ofs, otmp, err := makeOverlayFS(dfs) 74 | defer os.RemoveAll(otmp) 75 | assert.Equal(t, nil, err, nil) 76 | 77 | _, err = ofs.Create(name) 78 | defer ofs.RemoveAll(name) 79 | assert.Equal(t, nil, err, nil) 80 | 81 | existsOnDisk := dfs.Exists(name) 82 | assert.Equal(t, true, existsOnDisk, nil) 83 | } 84 | 85 | func TestOverlayFileSystemMkdir(t *testing.T) { 86 | tmp, err := ioutil.TempDir("", "test-terraform-provider-kustomization-*") 87 | defer os.RemoveAll(tmp) 88 | assert.Equal(t, nil, err, nil) 89 | name := filepath.Join(tmp, "test-mkdir") 90 | 91 | dfs := filesys.MakeFsOnDisk() 92 | ofs, otmp, err := makeOverlayFS(dfs) 93 | defer os.RemoveAll(otmp) 94 | assert.Equal(t, nil, err, nil) 95 | 96 | err = ofs.Mkdir(name) 97 | assert.Equal(t, nil, err, nil) 98 | 99 | existsOnDisk := dfs.Exists(name) 100 | assert.Equal(t, true, existsOnDisk, nil) 101 | } 102 | 103 | func TestOverlayFileSystemMkdirAll(t *testing.T) { 104 | tmp, err := ioutil.TempDir("", "test-terraform-provider-kustomization-*") 105 | defer os.RemoveAll(tmp) 106 | assert.Equal(t, nil, err, nil) 107 | 108 | name := filepath.Join(tmp, "test-mkdirall") 109 | 110 | dfs := filesys.MakeFsOnDisk() 111 | ofs, otmp, err := makeOverlayFS(dfs) 112 | defer os.RemoveAll(otmp) 113 | assert.Equal(t, nil, err, nil) 114 | 115 | err = ofs.MkdirAll(name) 116 | assert.Equal(t, nil, err, nil) 117 | 118 | existsOnDisk := dfs.Exists(name) 119 | assert.Equal(t, true, existsOnDisk, nil) 120 | } 121 | 122 | func TestOverlayFileSystemRemoveAll(t *testing.T) { 123 | tmp, err := ioutil.TempDir("", "test-terraform-provider-kustomization-*") 124 | defer os.RemoveAll(tmp) 125 | assert.Equal(t, nil, err, nil) 126 | 127 | name := filepath.Join(tmp, "test-mkdirall/test") 128 | 129 | dfs := filesys.MakeFsOnDisk() 130 | ofs, otmp, err := makeOverlayFS(dfs) 131 | defer os.RemoveAll(otmp) 132 | assert.Equal(t, nil, err, nil) 133 | 134 | ofs.MkdirAll(name) 135 | err = ofs.RemoveAll(name) 136 | assert.Equal(t, nil, err, nil) 137 | 138 | existsOnDisk := dfs.Exists(name) 139 | assert.Equal(t, false, existsOnDisk, nil) 140 | } 141 | 142 | func TestOverlayFileSystemOpen(t *testing.T) { 143 | tmp, err := ioutil.TempDir("", "test-terraform-provider-kustomization-*") 144 | defer os.RemoveAll(tmp) 145 | assert.Equal(t, nil, err, nil) 146 | 147 | name := filepath.Join(tmp, "test") 148 | 149 | dfs := filesys.MakeFsOnDisk() 150 | ofs, otmp, err := makeOverlayFS(dfs) 151 | defer os.RemoveAll(otmp) 152 | assert.Equal(t, nil, err, nil) 153 | 154 | ofs.Create(name) 155 | defer ofs.RemoveAll(name) 156 | 157 | _, err = ofs.Open(name) 158 | assert.Equal(t, nil, err, nil) 159 | 160 | _, err = dfs.Open(name) 161 | assert.Equal(t, nil, err, nil) 162 | } 163 | 164 | func TestOverlayFileSystemCleanedAbs(t *testing.T) { 165 | dfs := filesys.MakeFsOnDisk() 166 | ofs, otmp, err := makeOverlayFS(dfs) 167 | defer os.RemoveAll(otmp) 168 | assert.Equal(t, nil, err, nil) 169 | 170 | ofs.WriteFile(KFILENAME, []byte{}) 171 | defer ofs.RemoveAll(KFILENAME) 172 | 173 | cwd, cwderr := os.Getwd() 174 | assert.Equal(t, nil, cwderr, nil) 175 | kfilepath := filepath.Join(cwd, KFILENAME) 176 | 177 | dcd, dn, derr := dfs.CleanedAbs(kfilepath) 178 | assert.Equal(t, filesys.ConfirmedDir(""), dcd, nil) 179 | assert.Equal(t, "", dn, nil) 180 | assert.NotEqual(t, nil, derr, nil) 181 | 182 | // test the overlay fakes KFILENAME into the current working dir 183 | ocd, on, oerr := ofs.CleanedAbs(kfilepath) 184 | assert.Equal(t, filesys.ConfirmedDir(cwd), ocd, nil) 185 | assert.Equal(t, KFILENAME, on, nil) 186 | assert.Equal(t, nil, oerr, nil) 187 | 188 | // test neither kfilepath nor KFILENAME are on disk 189 | _, _, ederr := dfs.CleanedAbs(kfilepath) 190 | assert.NotEqual(t, nil, ederr, nil) 191 | 192 | _, _, ederr = dfs.CleanedAbs(KFILENAME) 193 | assert.NotEqual(t, nil, ederr, nil) 194 | } 195 | 196 | func TestOverlayFileSystemExists(t *testing.T) { 197 | tmp, err := ioutil.TempDir("", "test-terraform-provider-kustomization-*") 198 | defer os.RemoveAll(tmp) 199 | assert.Equal(t, nil, err, nil) 200 | name := filepath.Join(tmp, "test") 201 | 202 | dfs := filesys.MakeFsOnDisk() 203 | ofs, otmp, err := makeOverlayFS(dfs) 204 | defer os.RemoveAll(otmp) 205 | assert.Equal(t, nil, err, nil) 206 | 207 | ofs.Create(name) 208 | defer ofs.RemoveAll(name) 209 | 210 | c := ofs.Exists(name) 211 | assert.Equal(t, true, c, nil) 212 | } 213 | 214 | func TestOverlayFileSystemGlob(t *testing.T) { 215 | tmp, err := ioutil.TempDir("", "test-terraform-provider-kustomization-*") 216 | defer os.RemoveAll(tmp) 217 | assert.Equal(t, nil, err, nil) 218 | name := filepath.Join(tmp, "test") 219 | 220 | dfs := filesys.MakeFsOnDisk() 221 | ofs, otmp, err := makeOverlayFS(dfs) 222 | defer os.RemoveAll(otmp) 223 | assert.Equal(t, nil, err, nil) 224 | 225 | ofs.Create(name) 226 | defer ofs.RemoveAll(name) 227 | 228 | r, err := ofs.Glob(filepath.Join(tmp, "*")) 229 | assert.Equal(t, []string{name}, r, nil) 230 | assert.Equal(t, nil, err, nil) 231 | } 232 | 233 | func TestOverlayFileSystemIsDir(t *testing.T) { 234 | name := "test_kustomizations" 235 | 236 | dfs := filesys.MakeFsOnDisk() 237 | ofs, otmp, err := makeOverlayFS(dfs) 238 | defer os.RemoveAll(otmp) 239 | assert.Equal(t, nil, err, nil) 240 | 241 | dc := dfs.IsDir(name) 242 | assert.Equal(t, true, dc, nil) 243 | 244 | oc := ofs.IsDir(name) 245 | assert.Equal(t, dc, oc, nil) 246 | } 247 | 248 | func TestOverlayFileSystemReadFile(t *testing.T) { 249 | dfs := filesys.MakeFsOnDisk() 250 | ofs, otmp, err := makeOverlayFS(dfs) 251 | defer os.RemoveAll(otmp) 252 | assert.Equal(t, nil, err, nil) 253 | 254 | ofs.WriteFile(KFILENAME, []byte{}) 255 | 256 | cwd, cwderr := os.Getwd() 257 | assert.Equal(t, nil, cwderr, nil) 258 | kfilepath := filepath.Join(cwd, KFILENAME) 259 | 260 | // overlay the file is read with cwd as path 261 | od, oerr := ofs.ReadFile(kfilepath) 262 | assert.Equal(t, []byte{}, od, nil) 263 | assert.Equal(t, nil, oerr, nil) 264 | 265 | // the file is not on disk in cwd 266 | dd, derr := dfs.ReadFile(kfilepath) 267 | assert.Equal(t, []byte(nil), dd, nil) 268 | assert.NotEqual(t, nil, derr, nil) 269 | 270 | // the file is on disk in overlay tmp 271 | dd, derr = dfs.ReadFile(filepath.Join(otmp, KFILENAME)) 272 | assert.Equal(t, []byte{}, dd, nil) 273 | assert.Equal(t, nil, derr, nil) 274 | } 275 | 276 | func TestOverlayFileSystemWriteFile(t *testing.T) { 277 | dfs := filesys.MakeFsOnDisk() 278 | ofs, otmp, err := makeOverlayFS(dfs) 279 | defer os.RemoveAll(otmp) 280 | assert.Equal(t, nil, err, nil) 281 | 282 | // overlay write the file without path 283 | ed := []byte("test") 284 | oerr := ofs.WriteFile(KFILENAME, ed) 285 | assert.Equal(t, nil, oerr, nil) 286 | 287 | cwd, cwderr := os.Getwd() 288 | assert.Equal(t, nil, cwderr, nil) 289 | kfilepath := filepath.Join(cwd, KFILENAME) 290 | 291 | // overlay read the file with cwd path 292 | od, oerr := ofs.ReadFile(kfilepath) 293 | assert.Equal(t, ed, od, nil) 294 | assert.Equal(t, nil, oerr, nil) 295 | 296 | // on-disk file with cwd does not exist 297 | dd, derr := dfs.ReadFile(kfilepath) 298 | assert.Equal(t, []byte(nil), dd, nil) 299 | assert.NotEqual(t, nil, derr, nil) 300 | 301 | // on-disk file without cwd does not exist either 302 | dd, derr = dfs.ReadFile(KFILENAME) 303 | assert.Equal(t, []byte(nil), dd, nil) 304 | assert.NotEqual(t, nil, derr, nil) 305 | 306 | // on-disk file in overlay tmp does exist 307 | dd, derr = dfs.ReadFile(filepath.Join(otmp, KFILENAME)) 308 | assert.Equal(t, ed, dd, nil) 309 | assert.Equal(t, nil, derr, nil) 310 | } 311 | -------------------------------------------------------------------------------- /kustomize/data_source_kustomization_test.go: -------------------------------------------------------------------------------- 1 | package kustomize 2 | 3 | import ( 4 | "math" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func TestDeterminePrefix(t *testing.T) { 11 | for _, id := range residListFirst { 12 | kr := mustParseProviderId(id) 13 | p := determinePrefix(kr) 14 | e := uint32(1) 15 | assert.Equal(t, e, p, nil) 16 | } 17 | 18 | for _, id := range residListDefault { 19 | kr := mustParseProviderId(id) 20 | p := determinePrefix(kr) 21 | e := uint32(5) 22 | assert.Equal(t, e, p, nil) 23 | } 24 | 25 | for _, id := range residListLast { 26 | kr := mustParseProviderId(id) 27 | p := determinePrefix(kr) 28 | e := uint32(9) 29 | assert.Equal(t, e, p, nil) 30 | } 31 | } 32 | 33 | func TestPrefixHash(t *testing.T) { 34 | ti := uint32(math.MaxInt32 / 1000) 35 | i := prefixHash(uint32(1), ti) 36 | assert.Equal(t, 100021474, i, nil) 37 | 38 | i = prefixHash(uint32(5), ti) 39 | assert.Equal(t, 500021474, i, nil) 40 | 41 | i = prefixHash(uint32(9), ti) 42 | assert.Equal(t, 900021474, i, nil) 43 | } 44 | 45 | func TestPrefixHashMaxInt(t *testing.T) { 46 | ti := uint32(math.MaxInt32) 47 | i := prefixHash(uint32(1), ti) 48 | assert.Equal(t, 121474836, i, nil) 49 | 50 | i = prefixHash(uint32(5), ti) 51 | assert.Equal(t, 521474836, i, nil) 52 | 53 | i = prefixHash(uint32(9), ti) 54 | assert.Equal(t, 921474836, i, nil) 55 | } 56 | 57 | func TestIdSetHash(t *testing.T) { 58 | idList := []string{} 59 | idList = append(idList, residListFirst...) 60 | idList = append(idList, residListDefault...) 61 | idList = append(idList, residListLast...) 62 | setIDs := []int{} 63 | 64 | for _, s := range idList { 65 | f := idSetHash(s) 66 | 67 | assert.NotContains(t, setIDs, f, nil) 68 | setIDs = append(setIDs, f) 69 | } 70 | } 71 | 72 | var residListFirst = []string{ 73 | "_/Namespace/_/test", 74 | "apiextensions.k8s.io/CustomResourceDefinition/_/test", 75 | "apiextensions.k8s.io/CustomResourceDefinition/test-ns/test", 76 | } 77 | 78 | var residListDefault = []string{ 79 | "autoscaling/HorizontalPodAutoscaler/_/test", 80 | "autoscaling/HorizontalPodAutoscaler/test-ns/test", 81 | "coordination.k8s.io/Lease/_/test", 82 | "coordination.k8s.io/Lease/test-ns/test", 83 | "discovery.k8s.io/EndpointSlice/_/test", 84 | "discovery.k8s.io/EndpointSlice/test-ns/test", 85 | "extensions/Ingress/_/test", 86 | "extensions/Ingress/test-ns/test", 87 | "rbac.authorization.k8s.io/ClusterRoleBinding/_/test", 88 | "rbac.authorization.k8s.io/ClusterRoleBinding/test-ns/test", 89 | "rbac.authorization.k8s.io/ClusterRole/_/test", 90 | "rbac.authorization.k8s.io/ClusterRole/test-ns/test", 91 | "rbac.authorization.k8s.io/RoleBinding/_/test", 92 | "rbac.authorization.k8s.io/RoleBinding/test-ns/test", 93 | "rbac.authorization.k8s.io/Role/_/test", 94 | "rbac.authorization.k8s.io/Role/test-ns/test", 95 | "apiregistration.k8s.io/APIService/_/test", 96 | "apiregistration.k8s.io/APIService/test-ns/test", 97 | "batch/CronJob/_/test", 98 | "batch/CronJob/test-ns/test", 99 | "batch/Job/_/test", 100 | "batch/Job/test-ns/test", 101 | "authorization.k8s.io/LocalSubjectAccessReview/_/test", 102 | "authorization.k8s.io/LocalSubjectAccessReview/test-ns/test", 103 | "authorization.k8s.io/SelfSubjectAccessReview/_/test", 104 | "authorization.k8s.io/SelfSubjectAccessReview/test-ns/test", 105 | "authorization.k8s.io/SelfSubjectRulesReview/_/test", 106 | "authorization.k8s.io/SelfSubjectRulesReview/test-ns/test", 107 | "authorization.k8s.io/SubjectAccessReview/_/test", 108 | "authorization.k8s.io/SubjectAccessReview/test-ns/test", 109 | "certificates.k8s.io/CertificateSigningRequest/_/test", 110 | "certificates.k8s.io/CertificateSigningRequest/test-ns/test", 111 | "events.k8s.io/Event/_/test", 112 | "events.k8s.io/Event/test-ns/test", 113 | "node.k8s.io/RuntimeClass/_/test", 114 | "node.k8s.io/RuntimeClass/test-ns/test", 115 | "policy/PodDisruptionBudget/_/test", 116 | "policy/PodDisruptionBudget/test-ns/test", 117 | "policy/PodSecurityPolicy/_/test", 118 | "policy/PodSecurityPolicy/test-ns/test", 119 | "apps/ControllerRevision/_/test", 120 | "apps/ControllerRevision/test-ns/test", 121 | "apps/DaemonSet/_/test", 122 | "apps/DaemonSet/test-ns/test", 123 | "apps/Deployment/_/test", 124 | "apps/Deployment/test-ns/test", 125 | "apps/ReplicaSet/_/test", 126 | "apps/ReplicaSet/test-ns/test", 127 | "apps/StatefulSet/_/test", 128 | "apps/StatefulSet/test-ns/test", 129 | "authentication.k8s.io/TokenReview/_/test", 130 | "authentication.k8s.io/TokenReview/test-ns/test", 131 | "networking.k8s.io/IngressClass/_/test", 132 | "networking.k8s.io/IngressClass/test-ns/test", 133 | "networking.k8s.io/Ingress/_/test", 134 | "networking.k8s.io/Ingress/test-ns/test", 135 | "networking.k8s.io/NetworkPolicy/_/test", 136 | "networking.k8s.io/NetworkPolicy/test-ns/test", 137 | "scheduling.k8s.io/PriorityClass/_/test", 138 | "scheduling.k8s.io/PriorityClass/test-ns/test", 139 | "storage.k8s.io/CSIDriver/_/test", 140 | "storage.k8s.io/CSIDriver/test-ns/test", 141 | "storage.k8s.io/CSINode/_/test", 142 | "storage.k8s.io/CSINode/test-ns/test", 143 | "storage.k8s.io/StorageClass/_/test", 144 | "storage.k8s.io/StorageClass/test-ns/test", 145 | "storage.k8s.io/VolumeAttachment/_/test", 146 | "storage.k8s.io/VolumeAttachment/test-ns/test", 147 | "_/Binding/_/test", 148 | "_/Binding/test-ns/test", 149 | "_/ComponentStatus/_/test", 150 | "_/ComponentStatus/test-ns/test", 151 | "_/ConfigMap/_/test", 152 | "_/ConfigMap/test-ns/test", 153 | "_/Endpoints/_/test", 154 | "_/Endpoints/test-ns/test", 155 | "_/Event/_/test", 156 | "_/Event/test-ns/test", 157 | "_/LimitRange/_/test", 158 | "_/LimitRange/test-ns/test", 159 | "_/Node/_/test", 160 | "_/PersistentVolumeClaim/_/test", 161 | "_/PersistentVolumeClaim/test-ns/test", 162 | "_/PersistentVolume/_/test", 163 | "_/PersistentVolume/test-ns/test", 164 | "_/Pod/_/test", 165 | "_/Pod/test-ns/test", 166 | "_/PodTemplate/_/test", 167 | "_/PodTemplate/test-ns/test", 168 | "_/ReplicationController/_/test", 169 | "_/ReplicationController/test-ns/test", 170 | "_/ResourceQuota/_/test", 171 | "_/ResourceQuota/test-ns/test", 172 | "_/Secret/_/test", 173 | "_/Secret/test-ns/test", 174 | "_/ServiceAccount/_/test", 175 | "_/ServiceAccount/test-ns/test", 176 | "_/Service/_/test", 177 | "_/Service/test-ns/test", 178 | } 179 | 180 | var residListLast = []string{ 181 | "admissionregistration.k8s.io/MutatingWebhookConfiguration/_/test", 182 | "admissionregistration.k8s.io/MutatingWebhookConfiguration/test-ns/test", 183 | "admissionregistration.k8s.io/ValidatingWebhookConfiguration/_/test", 184 | "admissionregistration.k8s.io/ValidatingWebhookConfiguration/test-ns/test", 185 | } 186 | -------------------------------------------------------------------------------- /kustomize/manifest.go: -------------------------------------------------------------------------------- 1 | package kustomize 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | "strings" 8 | "time" 9 | 10 | "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" 11 | 12 | k8sappsv1 "k8s.io/api/apps/v1" 13 | k8serrors "k8s.io/apimachinery/pkg/api/errors" 14 | k8smeta "k8s.io/apimachinery/pkg/api/meta" 15 | k8smetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 16 | 17 | k8sunstructured "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" 18 | k8sruntime "k8s.io/apimachinery/pkg/runtime" 19 | k8sschema "k8s.io/apimachinery/pkg/runtime/schema" 20 | k8stypes "k8s.io/apimachinery/pkg/types" 21 | k8sdynamic "k8s.io/client-go/dynamic" 22 | "k8s.io/client-go/restmapper" 23 | ) 24 | 25 | var waitRefreshFunctions = map[string]waitRefreshFunction{ 26 | "apps/Deployment": waitDeploymentRefresh, 27 | "apps/DaemonSet": waitDaemonsetRefresh, 28 | "apps/StatefulSet": waitStatefulSetRefresh, 29 | } 30 | 31 | type kManifestId struct { 32 | group string 33 | kind string 34 | namespace string 35 | name string 36 | } 37 | 38 | type waitRefreshFunction func(km *kManifest) (interface{}, string, error) 39 | 40 | func mustParseProviderId(str string) *kManifestId { 41 | kr, err := parseProviderId(str) 42 | if err != nil { 43 | log.Fatal(err) 44 | } 45 | 46 | return kr 47 | } 48 | 49 | func parseProviderId(str string) (*kManifestId, error) { 50 | parts := strings.Split(str, "/") 51 | 52 | if len(parts) != 4 { 53 | return nil, fmt.Errorf("invalid ID: %q, valid IDs look like: \"_/Namespace/_/example\"", str) 54 | } 55 | 56 | group := parts[0] 57 | kind := parts[1] 58 | namespace := parts[2] 59 | name := parts[3] 60 | 61 | return &kManifestId{ 62 | group: underscoreToEmpty(group), 63 | kind: kind, 64 | namespace: underscoreToEmpty(namespace), 65 | name: name, 66 | }, nil 67 | } 68 | 69 | func (k kManifestId) string() string { 70 | return fmt.Sprintf("%s/%s/%s/%s", emptyToUnderscore(k.group), k.kind, emptyToUnderscore(k.namespace), k.name) 71 | } 72 | 73 | func underscoreToEmpty(value string) string { 74 | if value == "_" { 75 | return "" 76 | } 77 | return value 78 | } 79 | 80 | func emptyToUnderscore(value string) string { 81 | if value == "" { 82 | return "_" 83 | } 84 | return value 85 | } 86 | 87 | type kManifest struct { 88 | resource *k8sunstructured.Unstructured 89 | mapper *restmapper.DeferredDiscoveryRESTMapper 90 | client k8sdynamic.Interface 91 | json []byte 92 | } 93 | 94 | func newKManifest(mapper *restmapper.DeferredDiscoveryRESTMapper, client k8sdynamic.Interface) *kManifest { 95 | return &kManifest{ 96 | mapper: mapper, 97 | client: client, 98 | } 99 | } 100 | 101 | func (km *kManifest) load(body []byte) error { 102 | obj, err := k8sruntime.Decode(k8sunstructured.UnstructuredJSONScheme, body) 103 | if err != nil { 104 | return logError(fmt.Errorf("json error: %s", err)) 105 | } 106 | 107 | km.resource = obj.(*k8sunstructured.Unstructured) 108 | km.json = body 109 | 110 | return nil 111 | } 112 | 113 | func (km *kManifest) gvk() k8sschema.GroupVersionKind { 114 | return km.resource.GroupVersionKind() 115 | } 116 | 117 | func (km *kManifest) gvr() (k8sschema.GroupVersionResource, error) { 118 | m, err := km.mapping() 119 | return m.Resource, err 120 | } 121 | 122 | func (km *kManifest) mapping() (m *k8smeta.RESTMapping, err error) { 123 | return km.mapper.RESTMapping(km.gvk().GroupKind(), km.gvk().Version) 124 | } 125 | 126 | func (km *kManifest) mappings() (m []*k8smeta.RESTMapping, err error) { 127 | return km.mapper.RESTMappings(km.gvk().GroupKind()) 128 | } 129 | 130 | func (km *kManifest) namespace() string { 131 | return km.id().namespace 132 | } 133 | 134 | func (km *kManifest) isNamespaced() (bool, error) { 135 | m, err := km.mapping() 136 | if err != nil { 137 | return false, km.fmtErr(fmt.Errorf("api error: %s", err)) 138 | } 139 | 140 | if m.Scope.Name() == k8smeta.RESTScopeNameNamespace { 141 | return true, nil 142 | } 143 | 144 | return false, nil 145 | } 146 | 147 | func (km *kManifest) name() string { 148 | return km.id().name 149 | } 150 | 151 | func (km *kManifest) id() (id kManifestId) { 152 | id.group = km.gvk().Group 153 | id.kind = km.gvk().Kind 154 | id.namespace = km.resource.GetNamespace() 155 | id.name = km.resource.GetName() 156 | 157 | return id 158 | } 159 | 160 | func (km *kManifest) api() (api k8sdynamic.ResourceInterface, err error) { 161 | gvr, err := km.gvr() 162 | if err != nil { 163 | return api, km.fmtErr(fmt.Errorf("api error: %s", err)) 164 | } 165 | 166 | api = km.client.Resource(gvr) 167 | 168 | isNamespaced, err := km.isNamespaced() 169 | if err != nil { 170 | return api, km.fmtErr(fmt.Errorf("api error: %s", err)) 171 | } 172 | 173 | if isNamespaced { 174 | api = km.client.Resource(gvr).Namespace(km.namespace()) 175 | } 176 | 177 | return api, nil 178 | } 179 | 180 | func (km *kManifest) apiGet(opts k8smetav1.GetOptions) (resp *k8sunstructured.Unstructured, err error) { 181 | api, err := km.api() 182 | if err != nil { 183 | return resp, km.fmtErr(fmt.Errorf("get failed: %s", err)) 184 | } 185 | 186 | return api.Get(context.TODO(), km.name(), opts) 187 | } 188 | 189 | func (km *kManifest) apiCreate(opts k8smetav1.CreateOptions) (resp *k8sunstructured.Unstructured, err error) { 190 | api, err := km.api() 191 | if err != nil { 192 | return resp, km.fmtErr(fmt.Errorf("create failed: %s", err)) 193 | } 194 | 195 | return api.Create(context.TODO(), km.resource, opts) 196 | } 197 | 198 | func (km *kManifest) apiDelete(opts k8smetav1.DeleteOptions) (err error) { 199 | api, err := km.api() 200 | if err != nil { 201 | return km.fmtErr(fmt.Errorf("delete failed: %s", err)) 202 | } 203 | 204 | return api.Delete(context.TODO(), km.name(), opts) 205 | } 206 | 207 | func (km *kManifest) apiPreparePatch(kmo *kManifest, currAllowNotFound bool) (pt k8stypes.PatchType, p []byte, err error) { 208 | original := kmo.json 209 | modified := km.json 210 | 211 | resp, err := km.apiGet(k8smetav1.GetOptions{}) 212 | if err != nil { 213 | if !k8serrors.IsNotFound(err) || (k8serrors.IsNotFound(err) && !currAllowNotFound) { 214 | return pt, p, km.fmtErr(fmt.Errorf("error preparing patch: %s", err)) 215 | } 216 | } 217 | 218 | current, err := resp.MarshalJSON() 219 | if err != nil { 220 | return pt, p, km.fmtErr(fmt.Errorf("error preparing patch: %s", err)) 221 | } 222 | 223 | pt, p, err = getPatch(km.gvk(), original, modified, current) 224 | if err != nil { 225 | return pt, p, km.fmtErr(fmt.Errorf("error preparing patch: %s", err)) 226 | } 227 | 228 | return pt, p, nil 229 | } 230 | 231 | func (km *kManifest) apiPatch(pt k8stypes.PatchType, p []byte, opts k8smetav1.PatchOptions) (resp *k8sunstructured.Unstructured, err error) { 232 | api, err := km.api() 233 | if err != nil { 234 | return resp, km.fmtErr(fmt.Errorf("patch failed: %s", err)) 235 | } 236 | 237 | return api.Patch(context.TODO(), km.name(), pt, p, opts) 238 | } 239 | 240 | func parseResourceData(km *kManifest, d string) (err error) { 241 | b := []byte(d) 242 | 243 | err = km.load(b) 244 | if err != nil { 245 | return logError(fmt.Errorf("error parsing resource data: %s", err)) 246 | } 247 | 248 | return nil 249 | } 250 | 251 | func (km *kManifest) getNamespaceManifest() (kns *kManifest, namespaced bool) { 252 | if km.namespace() == "" { 253 | return kns, false 254 | } 255 | 256 | kns = newKManifest(km.mapper, km.client) 257 | 258 | kns.resource = kns.resource.NewEmptyInstance().(*k8sunstructured.Unstructured) 259 | 260 | gvk := k8sschema.GroupVersionKind{ 261 | Group: "", 262 | Version: "v1", 263 | Kind: "Namespace"} 264 | 265 | kns.resource.SetGroupVersionKind(gvk) 266 | kns.resource.SetName(km.namespace()) 267 | 268 | return kns, true 269 | } 270 | 271 | func (km *kManifest) waitKind(t time.Duration) error { 272 | stateConf := &resource.StateChangeConf{ 273 | Target: []string{"existing"}, 274 | Pending: []string{"pending"}, 275 | Timeout: t, 276 | Refresh: func() (interface{}, string, error) { 277 | mapping, err := km.mapping() 278 | if err != nil { 279 | if k8smeta.IsNoMatchError(err) { 280 | // if not found, reset mapper cache 281 | // before trying again (required for CRDs) 282 | km.mapper.Reset() 283 | return nil, "pending", nil 284 | } 285 | return nil, "", err 286 | } 287 | 288 | return mapping.Resource, "existing", nil 289 | }, 290 | } 291 | 292 | _, err := stateConf.WaitForState() 293 | if err != nil { 294 | return km.fmtErr(fmt.Errorf("timed out waiting for: %q: %s", km.gvk().String(), err)) 295 | } 296 | 297 | return nil 298 | } 299 | 300 | func (km *kManifest) waitNamespace(t time.Duration) error { 301 | kns, namespaced := km.getNamespaceManifest() 302 | if !namespaced { 303 | // if the resource is not namespaced 304 | // we don't have to wait for it 305 | return nil 306 | } 307 | 308 | // wait for the namespace to exist 309 | _, err := kns.mappings() 310 | if err != nil { 311 | return km.fmtErr( 312 | fmt.Errorf("api error %q: %s", kns.id().string(), err), 313 | ) 314 | } 315 | 316 | stateConf := &resource.StateChangeConf{ 317 | Target: []string{"existing"}, 318 | Pending: []string{"pending"}, 319 | Timeout: t, 320 | Refresh: func() (interface{}, string, error) { 321 | resp, err := kns.apiGet(k8smetav1.GetOptions{}) 322 | if err != nil { 323 | if k8serrors.IsNotFound(err) { 324 | return nil, "pending", nil 325 | } 326 | return nil, "", err 327 | } 328 | 329 | return resp, "existing", nil 330 | }, 331 | } 332 | 333 | _, err = stateConf.WaitForState() 334 | if err != nil { 335 | return km.fmtErr(fmt.Errorf("timed out waiting for: %q: %s", kns.id().string(), err)) 336 | } 337 | 338 | return nil 339 | } 340 | 341 | func (km *kManifest) waitDeleted(t time.Duration) error { 342 | stateConf := &resource.StateChangeConf{ 343 | Target: []string{}, 344 | Pending: []string{"deleting"}, 345 | Timeout: t, 346 | Refresh: func() (interface{}, string, error) { 347 | resp, err := km.apiGet(k8smetav1.GetOptions{}) 348 | if err != nil { 349 | if k8serrors.IsNotFound(err) { 350 | return nil, "", nil 351 | } 352 | return nil, "", err 353 | } 354 | 355 | return resp, "deleting", nil 356 | }, 357 | } 358 | 359 | _, err := stateConf.WaitForState() 360 | if err != nil { 361 | return km.fmtErr(fmt.Errorf("timed out deleting: %s", err)) 362 | } 363 | 364 | return nil 365 | } 366 | 367 | func daemonsetReady(u *k8sunstructured.Unstructured) (bool, error) { 368 | var daemonset k8sappsv1.DaemonSet 369 | if err := k8sruntime.DefaultUnstructuredConverter.FromUnstructured(u.UnstructuredContent(), &daemonset); err != nil { 370 | return false, err 371 | } 372 | if daemonset.Generation == daemonset.Status.ObservedGeneration && 373 | daemonset.Status.UpdatedNumberScheduled == daemonset.Status.DesiredNumberScheduled && 374 | daemonset.Status.NumberReady == daemonset.Status.DesiredNumberScheduled && 375 | daemonset.Status.NumberUnavailable == 0 { 376 | return true, nil 377 | } else { 378 | return false, nil 379 | } 380 | } 381 | 382 | func waitDaemonsetRefresh(km *kManifest) (interface{}, string, error) { 383 | resp, err := km.apiGet(k8smetav1.GetOptions{}) 384 | if err != nil { 385 | if k8serrors.IsNotFound(err) { 386 | return nil, "missing", nil 387 | } 388 | return nil, "error", err 389 | } 390 | ready, err := daemonsetReady(resp) 391 | if err != nil { 392 | return nil, "error", err 393 | } 394 | if ready { 395 | return resp, "done", nil 396 | } 397 | return nil, "in progress", nil 398 | } 399 | 400 | func deploymentReady(u *k8sunstructured.Unstructured) (bool, error) { 401 | var deployment k8sappsv1.Deployment 402 | if err := k8sruntime.DefaultUnstructuredConverter.FromUnstructured(u.UnstructuredContent(), &deployment); err != nil { 403 | return false, err 404 | } 405 | if deployment.Generation == deployment.Status.ObservedGeneration && 406 | deployment.Status.AvailableReplicas == *deployment.Spec.Replicas && 407 | deployment.Status.AvailableReplicas == deployment.Status.Replicas && 408 | deployment.Status.UnavailableReplicas == 0 { 409 | return true, nil 410 | } else { 411 | return false, nil 412 | } 413 | } 414 | 415 | func waitDeploymentRefresh(km *kManifest) (interface{}, string, error) { 416 | resp, err := km.apiGet(k8smetav1.GetOptions{}) 417 | if err != nil { 418 | if k8serrors.IsNotFound(err) { 419 | return nil, "missing", nil 420 | } 421 | return nil, "error", err 422 | } 423 | ready, err := deploymentReady(resp) 424 | if err != nil { 425 | return nil, "error", err 426 | } 427 | if ready { 428 | return resp, "done", nil 429 | } 430 | return nil, "in progress", nil 431 | } 432 | 433 | func statefulSetReady(u *k8sunstructured.Unstructured) (bool, error) { 434 | var statefulSet k8sappsv1.StatefulSet 435 | if err := k8sruntime.DefaultUnstructuredConverter.FromUnstructured(u.UnstructuredContent(), &statefulSet); err != nil { 436 | return false, err 437 | } 438 | if statefulSet.Generation == statefulSet.Status.ObservedGeneration && 439 | statefulSet.Status.AvailableReplicas == *statefulSet.Spec.Replicas && 440 | statefulSet.Status.AvailableReplicas == statefulSet.Status.Replicas { 441 | return true, nil 442 | } else { 443 | return false, nil 444 | } 445 | } 446 | 447 | func waitStatefulSetRefresh(km *kManifest) (interface{}, string, error) { 448 | resp, err := km.apiGet(k8smetav1.GetOptions{}) 449 | if err != nil { 450 | if k8serrors.IsNotFound(err) { 451 | return nil, "missing", nil 452 | } 453 | return nil, "error", err 454 | } 455 | ready, err := statefulSetReady(resp) 456 | if err != nil { 457 | return nil, "error", err 458 | } 459 | if ready { 460 | return resp, "done", nil 461 | } 462 | return nil, "in progress", nil 463 | } 464 | 465 | func (km *kManifest) waitCreatedOrUpdated(t time.Duration) error { 466 | gvk := km.gvk() 467 | if refresh, ok := waitRefreshFunctions[fmt.Sprintf("%s/%s", gvk.Group, gvk.Kind)]; ok { 468 | delay := 10 * time.Second 469 | stateConf := &resource.StateChangeConf{ 470 | Target: []string{"done"}, 471 | Pending: []string{"in progress"}, 472 | Timeout: t, 473 | Delay: delay, 474 | NotFoundChecks: 2*int(t/delay) + 1, 475 | Refresh: func() (interface{}, string, error) { 476 | return refresh(km) 477 | }, 478 | } 479 | 480 | _, err := stateConf.WaitForState() 481 | if err != nil { 482 | return km.fmtErr(fmt.Errorf("timed out creating/updating %s %s/%s: %s", gvk.Kind, km.namespace(), km.name(), err)) 483 | } 484 | } 485 | return nil 486 | } 487 | 488 | func (km *kManifest) fmtErr(err error) error { 489 | return fmt.Errorf( 490 | "%q: %s", 491 | km.id().string(), 492 | err) 493 | } 494 | -------------------------------------------------------------------------------- /kustomize/manifest_test.go: -------------------------------------------------------------------------------- 1 | package kustomize 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestKManifestLoad(t *testing.T) { 10 | ns := []byte(`{ 11 | "kind": "Namespace", 12 | "apiVersion": "v1", 13 | "metadata": { 14 | "name": "test", 15 | "creationTimestamp": null 16 | }, 17 | "spec": {}, 18 | "status": {} 19 | }`) 20 | 21 | km := kManifest{} 22 | err := km.load(ns) 23 | 24 | assert.Equal(t, nil, err) 25 | } 26 | 27 | func TestKManifestLoadErr(t *testing.T) { 28 | ns := []byte("") 29 | 30 | km := kManifest{} 31 | err := km.load(ns) 32 | 33 | assert.NotEqual(t, nil, err) 34 | } 35 | -------------------------------------------------------------------------------- /kustomize/provider.go: -------------------------------------------------------------------------------- 1 | package kustomize 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "sync" 7 | 8 | "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" 9 | 10 | "k8s.io/client-go/discovery" 11 | "k8s.io/client-go/discovery/cached/memory" 12 | "k8s.io/client-go/dynamic" 13 | _ "k8s.io/client-go/plugin/pkg/client/auth" 14 | "k8s.io/client-go/rest" 15 | "k8s.io/client-go/restmapper" 16 | "k8s.io/client-go/tools/clientcmd" 17 | 18 | "github.com/mitchellh/go-homedir" 19 | ) 20 | 21 | // Config ... 22 | type Config struct { 23 | Client dynamic.Interface 24 | Mapper *restmapper.DeferredDiscoveryRESTMapper 25 | Mutex *sync.Mutex 26 | GzipLastAppliedConfig bool 27 | } 28 | 29 | // Provider ... 30 | func Provider() *schema.Provider { 31 | p := &schema.Provider{ 32 | ResourcesMap: map[string]*schema.Resource{ 33 | "kustomization_resource": kustomizationResource(), 34 | }, 35 | 36 | DataSourcesMap: map[string]*schema.Resource{ 37 | // legacy name of the data source 38 | "kustomization": dataSourceKustomization(), 39 | // new name for the data source 40 | "kustomization_build": dataSourceKustomization(), 41 | 42 | // define overlay from TF 43 | "kustomization_overlay": dataSourceKustomizationOverlay(), 44 | }, 45 | 46 | Schema: map[string]*schema.Schema{ 47 | "kubeconfig_path": { 48 | Type: schema.TypeString, 49 | Optional: true, 50 | DefaultFunc: schema.EnvDefaultFunc("KUBECONFIG_PATH", nil), 51 | ExactlyOneOf: []string{"kubeconfig_path", "kubeconfig_raw", "kubeconfig_incluster"}, 52 | Description: "Path to a kubeconfig file. Can be set using KUBECONFIG_PATH env var", 53 | }, 54 | "kubeconfig_raw": { 55 | Type: schema.TypeString, 56 | Optional: true, 57 | ExactlyOneOf: []string{"kubeconfig_path", "kubeconfig_raw", "kubeconfig_incluster"}, 58 | Description: "Raw kube config. If kubeconfig_raw is set, KUBECONFIG_PATH is ignored.", 59 | }, 60 | "kubeconfig_incluster": { 61 | Type: schema.TypeBool, 62 | Optional: true, 63 | ExactlyOneOf: []string{"kubeconfig_path", "kubeconfig_raw", "kubeconfig_incluster"}, 64 | Description: "Set to true when running inside a kubernetes cluster. If kubeconfig_incluster is set, KUBECONFIG_PATH is ignored.", 65 | }, 66 | "context": { 67 | Type: schema.TypeString, 68 | Optional: true, 69 | DefaultFunc: schema.EnvDefaultFunc("KUBECONFIG_CONTEXT", nil), 70 | Description: "Context to use in kubeconfig with multiple contexts, if not specified the default context is to be used.", 71 | }, 72 | "gzip_last_applied_config": { 73 | Type: schema.TypeBool, 74 | Optional: true, 75 | Default: true, 76 | Description: "When 'true' compress the lastAppliedConfig annotation for resources that otherwise would exceed K8s' max annotation size. All other resources use the regular uncompressed annotation. Set to 'false' to disable compression entirely.", 77 | }, 78 | }, 79 | } 80 | 81 | p.ConfigureFunc = func(d *schema.ResourceData) (interface{}, error) { 82 | var config *rest.Config 83 | var err error 84 | 85 | raw := d.Get("kubeconfig_raw").(string) 86 | path := d.Get("kubeconfig_path").(string) 87 | incluster := d.Get("kubeconfig_incluster").(bool) 88 | context := d.Get("context").(string) 89 | 90 | if raw != "" { 91 | config, err = getClientConfig([]byte(raw), context) 92 | if err != nil { 93 | return nil, fmt.Errorf("provider kustomization: kubeconfig_raw: %s", err) 94 | } 95 | } 96 | 97 | if raw == "" && path != "" { 98 | data, err := readKubeconfigFile(path) 99 | if err != nil { 100 | return nil, fmt.Errorf("provider kustomization: kubeconfig_path: %s", err) 101 | } 102 | 103 | config, err = getClientConfig(data, context) 104 | if err != nil { 105 | return nil, fmt.Errorf("provider kustomization: kubeconfig_path: %s", err) 106 | } 107 | } 108 | 109 | if incluster { 110 | config, err = rest.InClusterConfig() 111 | if err != nil { 112 | return nil, fmt.Errorf("provider kustomization: couldn't load in cluster config: %s", err) 113 | } 114 | } 115 | 116 | // empty default config required to support 117 | // using a cluster resource or data source 118 | // that may not exist yet, to configure the provider 119 | if config == nil { 120 | config = &rest.Config{} 121 | } 122 | 123 | // Increase QPS and Burst rate limits 124 | config.QPS = 120 125 | config.Burst = 240 126 | 127 | client, err := dynamic.NewForConfig(config) 128 | if err != nil { 129 | return nil, fmt.Errorf("provider kustomization: %s", err) 130 | } 131 | 132 | dc, err := discovery.NewDiscoveryClientForConfig(config) 133 | if err != nil { 134 | return nil, fmt.Errorf("provider kustomization: %s", err) 135 | } 136 | 137 | mapper := restmapper.NewDeferredDiscoveryRESTMapper(memory.NewMemCacheClient(dc)) 138 | 139 | // Mutex to prevent parallel Kustomizer runs 140 | // temp workaround for upstream bug 141 | // https://github.com/kubernetes-sigs/kustomize/issues/3659 142 | mu := &sync.Mutex{} 143 | 144 | gzipLastAppliedConfig := d.Get("gzip_last_applied_config").(bool) 145 | 146 | return &Config{client, mapper, mu, gzipLastAppliedConfig}, nil 147 | } 148 | 149 | return p 150 | } 151 | 152 | func readKubeconfigFile(s string) ([]byte, error) { 153 | p, err := homedir.Expand(s) 154 | if err != nil { 155 | return nil, err 156 | } 157 | 158 | data, err := ioutil.ReadFile(p) 159 | if err != nil { 160 | return nil, err 161 | } 162 | 163 | return data, nil 164 | } 165 | 166 | func getClientConfig(data []byte, context string) (*rest.Config, error) { 167 | if len(context) == 0 { 168 | return clientcmd.RESTConfigFromKubeConfig(data) 169 | } 170 | 171 | rawConfig, err := clientcmd.Load(data) 172 | if err != nil { 173 | return nil, err 174 | } 175 | 176 | var clientConfig clientcmd.ClientConfig = clientcmd.NewNonInteractiveClientConfig( 177 | *rawConfig, 178 | context, 179 | &clientcmd.ConfigOverrides{CurrentContext: context}, 180 | nil) 181 | 182 | return clientConfig.ClientConfig() 183 | } 184 | -------------------------------------------------------------------------------- /kustomize/provider_test.go: -------------------------------------------------------------------------------- 1 | package kustomize 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" 7 | ) 8 | 9 | var testAccProviders map[string]*schema.Provider 10 | var testAccProvider *schema.Provider 11 | 12 | func init() { 13 | testAccProvider = Provider() 14 | testAccProviders = map[string]*schema.Provider{ 15 | "kustomization": testAccProvider, 16 | } 17 | } 18 | 19 | func TestProvider(t *testing.T) { 20 | provider := Provider() 21 | if err := provider.InternalValidate(); err != nil { 22 | t.Fatalf("err: %s", err) 23 | } 24 | } 25 | 26 | func TestProvider_impl(t *testing.T) { 27 | var _ schema.Provider = *Provider() 28 | } 29 | -------------------------------------------------------------------------------- /kustomize/resource_kustomization.go: -------------------------------------------------------------------------------- 1 | package kustomize 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "fmt" 7 | "strings" 8 | "time" 9 | 10 | "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" 11 | 12 | k8scorev1 "k8s.io/api/core/v1" 13 | k8serrors "k8s.io/apimachinery/pkg/api/errors" 14 | k8smeta "k8s.io/apimachinery/pkg/api/meta" 15 | k8smetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 16 | k8sschema "k8s.io/apimachinery/pkg/runtime/schema" 17 | "k8s.io/apimachinery/pkg/util/validation/field" 18 | ) 19 | 20 | func kustomizationResource() *schema.Resource { 21 | return &schema.Resource{ 22 | Create: kustomizationResourceCreate, 23 | Read: kustomizationResourceRead, 24 | Exists: kustomizationResourceExists, 25 | Update: kustomizationResourceUpdate, 26 | Delete: kustomizationResourceDelete, 27 | CustomizeDiff: kustomizationResourceDiff, 28 | 29 | Importer: &schema.ResourceImporter{ 30 | State: kustomizationResourceImport, 31 | }, 32 | 33 | Schema: map[string]*schema.Schema{ 34 | "manifest": &schema.Schema{ 35 | Type: schema.TypeString, 36 | Required: true, 37 | }, 38 | "wait": &schema.Schema{ 39 | Type: schema.TypeBool, 40 | Default: false, 41 | Optional: true, 42 | }, 43 | }, 44 | 45 | Timeouts: &schema.ResourceTimeout{ 46 | Create: schema.DefaultTimeout(5 * time.Minute), 47 | Update: schema.DefaultTimeout(5 * time.Minute), 48 | Delete: schema.DefaultTimeout(10 * time.Minute), 49 | }, 50 | } 51 | } 52 | 53 | func kustomizationResourceCreate(d *schema.ResourceData, m interface{}) error { 54 | mapper := m.(*Config).Mapper 55 | client := m.(*Config).Client 56 | km := newKManifest(mapper, client) 57 | 58 | err := km.load([]byte(d.Get("manifest").(string))) 59 | if err != nil { 60 | return logError(err) 61 | } 62 | 63 | // required for CRDs 64 | err = km.waitKind(d.Timeout(schema.TimeoutCreate)) 65 | if err != nil { 66 | return logError(err) 67 | } 68 | 69 | // required for namespaced resources 70 | err = km.waitNamespace(d.Timeout(schema.TimeoutCreate)) 71 | if err != nil { 72 | return logError(err) 73 | } 74 | 75 | // for secrets of type service account token 76 | // wait for service account to exist 77 | // https://github.com/kubernetes/kubernetes/issues/109401 78 | if (km.gvk().Kind == "Secret") && 79 | (km.resource.UnstructuredContent()["type"] != nil) && 80 | (km.resource.UnstructuredContent()["type"].(string) == string(k8scorev1.SecretTypeServiceAccountToken)) { 81 | 82 | annotations := km.resource.GetAnnotations() 83 | for k, v := range annotations { 84 | if k == k8scorev1.ServiceAccountNameKey { 85 | saGvk := k8sschema.GroupVersionKind{ 86 | Group: "", 87 | Version: "v1", 88 | Kind: "ServiceAccount"} 89 | mapping, err := mapper.RESTMapping(saGvk.GroupKind(), saGvk.GroupVersion().Version) 90 | if err != nil { 91 | return logError(km.fmtErr( 92 | fmt.Errorf("api error: %q: %s", saGvk.String(), err), 93 | )) 94 | } 95 | 96 | _, err = waitForGVKCreated(d, client, mapping, km.namespace(), v) 97 | if err != nil { 98 | return logError(km.fmtErr(fmt.Errorf("timed out waiting for: %q: %s", km.id().string(), err))) 99 | } 100 | } 101 | } 102 | } 103 | 104 | gzipLastAppliedConfig := m.(*Config).GzipLastAppliedConfig 105 | setLastAppliedConfig(km, gzipLastAppliedConfig) 106 | 107 | resp, err := km.apiCreate(k8smetav1.CreateOptions{}) 108 | if err != nil { 109 | return logError(err) 110 | } 111 | 112 | if d.Get("wait").(bool) { 113 | if err = km.waitCreatedOrUpdated(d.Timeout(schema.TimeoutCreate)); err != nil { 114 | return logError(err) 115 | } 116 | } 117 | 118 | id := string(resp.GetUID()) 119 | d.SetId(id) 120 | 121 | d.Set("manifest", getLastAppliedConfig(resp, gzipLastAppliedConfig)) 122 | 123 | return kustomizationResourceRead(d, m) 124 | } 125 | 126 | func kustomizationResourceRead(d *schema.ResourceData, m interface{}) error { 127 | km := newKManifest(m.(*Config).Mapper, m.(*Config).Client) 128 | 129 | err := km.load([]byte(d.Get("manifest").(string))) 130 | if err != nil { 131 | return logError(err) 132 | } 133 | 134 | resp, err := km.apiGet(k8smetav1.GetOptions{}) 135 | if err != nil { 136 | return logError(err) 137 | } 138 | 139 | id := string(resp.GetUID()) 140 | d.SetId(id) 141 | 142 | d.Set("manifest", getLastAppliedConfig(resp, m.(*Config).GzipLastAppliedConfig)) 143 | 144 | return nil 145 | } 146 | 147 | func kustomizationResourceExists(d *schema.ResourceData, m interface{}) (bool, error) { 148 | km := newKManifest(m.(*Config).Mapper, m.(*Config).Client) 149 | 150 | err := km.load([]byte(d.Get("manifest").(string))) 151 | if err != nil { 152 | return false, logError(err) 153 | } 154 | 155 | err = km.waitKind(d.Timeout(schema.TimeoutCreate)) 156 | if err != nil { 157 | if k8smeta.IsNoMatchError(err) { 158 | // If the Kind does not exist in the K8s API, 159 | // the resource can't exist either 160 | return false, nil 161 | } 162 | return false, logError(err) 163 | } 164 | 165 | _, err = km.apiGet(k8smetav1.GetOptions{}) 166 | if err != nil { 167 | if k8serrors.IsNotFound(err) { 168 | return false, nil 169 | } 170 | return false, logError(err) 171 | } 172 | 173 | return true, nil 174 | } 175 | 176 | func kustomizationResourceDiff(ctx context.Context, d *schema.ResourceDiff, m interface{}) error { 177 | if !d.HasChange("manifest") { 178 | return nil 179 | } 180 | 181 | client := m.(*Config).Client 182 | mapper := m.(*Config).Mapper 183 | gzipLastAppliedConfig := m.(*Config).GzipLastAppliedConfig 184 | 185 | do, dm := d.GetChange("manifest") 186 | 187 | kmm := newKManifest(mapper, client) 188 | err := kmm.load([]byte(dm.(string))) 189 | if err != nil { 190 | return logError(err) 191 | } 192 | setLastAppliedConfig(kmm, gzipLastAppliedConfig) 193 | 194 | _, err = kmm.mappings() 195 | if err != nil { 196 | // if there are no mappings we can't dry-run 197 | // this is for CRDs that do not exist yet 198 | return nil 199 | } 200 | 201 | isNamespaced, err := kmm.isNamespaced() 202 | if err != nil { 203 | return logError(err) 204 | } 205 | if isNamespaced && kmm.namespace() == "" { 206 | err = kmm.fmtErr(fmt.Errorf("is namespace scoped and must set metadata.namespace")) 207 | return logError(err) 208 | } 209 | if !isNamespaced && kmm.namespace() != "" { 210 | err = kmm.fmtErr(fmt.Errorf("is not namespace scoped but has metadata.namespace set")) 211 | return logError(err) 212 | } 213 | 214 | if do.(string) == "" { 215 | // diffing for create 216 | _, err = kmm.apiCreate(k8smetav1.CreateOptions{DryRun: []string{k8smetav1.DryRunAll}}) 217 | if err != nil { 218 | if k8serrors.IsAlreadyExists(err) { 219 | // this is an edge case during tests 220 | // get change above has empty original 221 | // yet the create request fails with 222 | // Error running pre-apply refresh 223 | return nil 224 | } 225 | 226 | if k8serrors.IsNotFound(err) { 227 | // we're dry-running a create 228 | // the notfound seems mostly the namespace 229 | return nil 230 | } 231 | 232 | return logError(kmm.fmtErr(err)) 233 | } 234 | 235 | return nil 236 | } 237 | 238 | // diffing for update 239 | kmo := newKManifest(mapper, client) 240 | err = kmo.load([]byte(do.(string))) 241 | if err != nil { 242 | return logError(err) 243 | } 244 | setLastAppliedConfig(kmo, gzipLastAppliedConfig) 245 | 246 | if kmo.name() != kmm.name() || kmo.namespace() != kmm.namespace() { 247 | // if the resource name or namespace changes, we can't patch but have to destroy and re-create 248 | d.ForceNew("manifest") 249 | return nil 250 | } 251 | 252 | pt, p, err := kmm.apiPreparePatch(kmo, true) 253 | if err != nil { 254 | return logError(err) 255 | } 256 | 257 | dryRunPatch := k8smetav1.PatchOptions{DryRun: []string{k8smetav1.DryRunAll}} 258 | 259 | _, err = kmm.apiPatch(pt, p, dryRunPatch) 260 | if err != nil { 261 | // Handle specific invalid errors 262 | if k8serrors.IsInvalid(err) { 263 | as := err.(k8serrors.APIStatus).Status() 264 | 265 | // ForceNew only when exact single cause 266 | if len(as.Details.Causes) == 1 { 267 | msg := as.Details.Causes[0].Message 268 | 269 | // if cause is immutable field force a delete and re-create plan 270 | if k8serrors.HasStatusCause(err, k8smetav1.CauseTypeFieldValueInvalid) && strings.HasSuffix(msg, ": field is immutable") == true { 271 | d.ForceNew("manifest") 272 | return nil 273 | } 274 | 275 | // if cause is statefulset forbidden fields error force a delete and re-create plan 276 | if k8serrors.HasStatusCause(err, k8smetav1.CauseType(field.ErrorTypeForbidden)) && strings.HasPrefix(msg, "Forbidden: updates to statefulset spec for fields") == true { 277 | d.ForceNew("manifest") 278 | return nil 279 | } 280 | 281 | // if cause is cannot change roleRef force a delete and re-create plan 282 | if k8serrors.HasStatusCause(err, k8smetav1.CauseTypeFieldValueInvalid) && strings.HasSuffix(msg, ": cannot change roleRef") == true { 283 | d.ForceNew("manifest") 284 | return nil 285 | } 286 | 287 | // if cause is updates to storage class provisioner or parameters are forbidden force a delete and re-create plan 288 | if k8serrors.HasStatusCause(err, k8smetav1.CauseType(field.ErrorTypeForbidden)) { 289 | if strings.HasSuffix(msg, ": updates to provisioner are forbidden.") || strings.HasPrefix(msg, "Forbidden: updates to parameters are forbidden") { 290 | d.ForceNew("manifest") 291 | return nil 292 | } 293 | } 294 | 295 | } 296 | } 297 | 298 | return logError(err) 299 | } 300 | 301 | return nil 302 | } 303 | 304 | func kustomizationResourceUpdate(d *schema.ResourceData, m interface{}) error { 305 | client := m.(*Config).Client 306 | mapper := m.(*Config).Mapper 307 | gzipLastAppliedConfig := m.(*Config).GzipLastAppliedConfig 308 | 309 | do, dm := d.GetChange("manifest") 310 | 311 | kmo := newKManifest(mapper, client) 312 | err := kmo.load([]byte(do.(string))) 313 | if err != nil { 314 | return logError(err) 315 | } 316 | 317 | kmm := newKManifest(mapper, client) 318 | err = kmm.load([]byte(dm.(string))) 319 | if err != nil { 320 | return logError(err) 321 | } 322 | 323 | if !d.HasChange("manifest") && !d.HasChange("wait") { 324 | return logError(kmm.fmtErr( 325 | errors.New("update called without diff"), 326 | )) 327 | } 328 | 329 | setLastAppliedConfig(kmo, gzipLastAppliedConfig) 330 | setLastAppliedConfig(kmm, gzipLastAppliedConfig) 331 | 332 | pt, p, err := kmm.apiPreparePatch(kmo, false) 333 | if err != nil { 334 | return logError(err) 335 | } 336 | 337 | resp, err := kmm.apiPatch(pt, p, k8smetav1.PatchOptions{}) 338 | if err != nil { 339 | return logError(err) 340 | } 341 | 342 | if d.Get("wait").(bool) { 343 | if err = kmm.waitCreatedOrUpdated(d.Timeout(schema.TimeoutUpdate)); err != nil { 344 | return logError(err) 345 | } 346 | } 347 | 348 | id := string(resp.GetUID()) 349 | d.SetId(id) 350 | 351 | d.Set("manifest", getLastAppliedConfig(resp, gzipLastAppliedConfig)) 352 | 353 | return kustomizationResourceRead(d, m) 354 | } 355 | 356 | func kustomizationResourceDelete(d *schema.ResourceData, m interface{}) error { 357 | client := m.(*Config).Client 358 | mapper := m.(*Config).Mapper 359 | 360 | km := newKManifest(mapper, client) 361 | 362 | err := parseResourceData(km, d.Get("manifest").(string)) 363 | if err != nil { 364 | return logError(err) 365 | } 366 | 367 | // look for all versions of the GroupKind in case the resource uses a 368 | // version that is no longer current 369 | _, err = km.mappings() 370 | if err != nil { 371 | if k8smeta.IsNoMatchError(err) { 372 | // If the Kind does not exist in the K8s API, 373 | // the resource can't exist either 374 | return nil 375 | } 376 | return logError(km.fmtErr(err)) 377 | } 378 | 379 | err = km.apiDelete(k8smetav1.DeleteOptions{}) 380 | if err != nil { 381 | // Consider not found during deletion a success 382 | if k8serrors.IsNotFound(err) { 383 | d.SetId("") 384 | return nil 385 | } 386 | 387 | return logError(err) 388 | } 389 | 390 | err = km.waitDeleted(d.Timeout(schema.TimeoutDelete)) 391 | if err != nil { 392 | return logError(err) 393 | } 394 | 395 | d.SetId("") 396 | 397 | return nil 398 | } 399 | 400 | func kustomizationResourceImport(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { 401 | client := m.(*Config).Client 402 | mapper := m.(*Config).Mapper 403 | gzipLastAppliedConfig := m.(*Config).GzipLastAppliedConfig 404 | 405 | k, err := parseProviderId(d.Id()) 406 | if err != nil { 407 | return nil, logError(err) 408 | } 409 | gk := k8sschema.GroupKind{Group: k.group, Kind: k.kind} 410 | 411 | // We don't need to use a specific API version here, as we're going to store the 412 | // resource using the LastAppliedConfig information which we can get from any 413 | // API version 414 | mappings, err := mapper.RESTMappings(gk) 415 | if err != nil { 416 | return nil, logError( 417 | fmt.Errorf("api error \"%s/%s/%s/%s\": %s", gk.Group, gk.Kind, k.namespace, k.name, err), 418 | ) 419 | } 420 | 421 | resp, err := client. 422 | Resource(mappings[0].Resource). 423 | Namespace(k.namespace). 424 | Get(context.TODO(), k.name, k8smetav1.GetOptions{}) 425 | if err != nil { 426 | return nil, logError( 427 | fmt.Errorf("\"%s/%s/%s/%s\": %s", gk.Group, gk.Kind, k.namespace, k.name, err), 428 | ) 429 | } 430 | 431 | id := string(resp.GetUID()) 432 | d.SetId(id) 433 | 434 | lac := getLastAppliedConfig(resp, gzipLastAppliedConfig) 435 | if lac == "" { 436 | return nil, logError( 437 | fmt.Errorf("\"%s/%s/%s/%s\": can not import resources without %q or %q annotation", gk.Group, gk.Kind, k.namespace, k.name, lastAppliedConfigAnnotation, gzipLastAppliedConfigAnnotation), 438 | ) 439 | } 440 | 441 | d.Set("manifest", lac) 442 | d.Set("wait", d.Get("wait")) 443 | 444 | return []*schema.ResourceData{d}, nil 445 | } 446 | -------------------------------------------------------------------------------- /kustomize/resource_kustomization_waitfor.go: -------------------------------------------------------------------------------- 1 | package kustomize 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" 7 | "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" 8 | 9 | k8serrors "k8s.io/apimachinery/pkg/api/errors" 10 | k8smeta "k8s.io/apimachinery/pkg/api/meta" 11 | k8smetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 12 | "k8s.io/client-go/dynamic" 13 | ) 14 | 15 | func waitForGVKCreated(d *schema.ResourceData, client dynamic.Interface, mapping *k8smeta.RESTMapping, namespace string, name string) (interface{}, error) { 16 | stateConf := &resource.StateChangeConf{ 17 | Target: []string{"existing"}, 18 | Pending: []string{"pending"}, 19 | Timeout: d.Timeout(schema.TimeoutCreate), 20 | Refresh: func() (interface{}, string, error) { 21 | resp, err := client. 22 | Resource(mapping.Resource). 23 | Namespace(namespace). 24 | Get(context.TODO(), name, k8smetav1.GetOptions{}) 25 | if err != nil { 26 | if k8serrors.IsNotFound(err) { 27 | return nil, "pending", nil 28 | } 29 | return nil, "", err 30 | } 31 | 32 | return resp, "existing", nil 33 | }, 34 | } 35 | 36 | return stateConf.WaitForState() 37 | } 38 | -------------------------------------------------------------------------------- /kustomize/structures_kustomization.go: -------------------------------------------------------------------------------- 1 | package kustomize 2 | 3 | import ( 4 | "sigs.k8s.io/kustomize/api/resmap" 5 | ) 6 | 7 | func flattenKustomizationIDs(rm resmap.ResMap) (ids []string, idsPrio [][]string, err error) { 8 | p0 := []string{} 9 | p1 := []string{} 10 | p2 := []string{} 11 | for _, id := range rm.AllIds() { 12 | kr := &kManifestId{ 13 | group: id.Group, 14 | kind: id.Kind, 15 | namespace: id.Namespace, 16 | name: id.Name, 17 | } 18 | 19 | ids = append(ids, kr.string()) 20 | 21 | p := determinePrefix(kr) 22 | if p < 5 { 23 | p0 = append(p0, kr.string()) 24 | } else if p == 9 { 25 | p2 = append(p2, kr.string()) 26 | } else { 27 | p1 = append(p1, kr.string()) 28 | } 29 | } 30 | 31 | idsPrio = append(idsPrio, p0) 32 | idsPrio = append(idsPrio, p1) 33 | idsPrio = append(idsPrio, p2) 34 | 35 | return ids, idsPrio, nil 36 | } 37 | 38 | func flattenKustomizationResources(rm resmap.ResMap) (res map[string]string, err error) { 39 | res = make(map[string]string) 40 | for _, r := range rm.Resources() { 41 | kr := &kManifestId{ 42 | group: r.CurId().Group, 43 | kind: r.CurId().Kind, 44 | namespace: r.GetNamespace(), 45 | name: r.GetName(), 46 | } 47 | 48 | json, err := r.MarshalJSON() 49 | if err != nil { 50 | return nil, err 51 | } 52 | res[kr.string()] = string(json) 53 | } 54 | return res, nil 55 | } 56 | -------------------------------------------------------------------------------- /kustomize/structures_kustomization_test.go: -------------------------------------------------------------------------------- 1 | package kustomize 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | "sigs.k8s.io/kustomize/api/krusty" 8 | "sigs.k8s.io/kustomize/kyaml/filesys" 9 | ) 10 | 11 | func TestConvertKustomizationIDs(t *testing.T) { 12 | fSys := filesys.MakeFsOnDisk() 13 | opts := krusty.MakeDefaultOptions() 14 | k := krusty.MakeKustomizer(opts) 15 | 16 | rm, err := k.Run(fSys, "test_kustomizations/basic/initial") 17 | assert.Equal(t, err, nil, nil) 18 | 19 | ids, idsPrio, err := flattenKustomizationIDs(rm) 20 | assert.Equal(t, err, nil, nil) 21 | 22 | expMerged := append(idsPrio[0], idsPrio[1]...) 23 | expMerged = append(expMerged, idsPrio[2]...) 24 | assert.ElementsMatch(t, expMerged, ids, nil) 25 | 26 | expIds := []string{"_/Namespace/_/test-basic", "apps/Deployment/test-basic/test", "networking.k8s.io/Ingress/test-basic/test", "_/Service/test-basic/test"} 27 | assert.ElementsMatch(t, expIds, ids, nil) 28 | 29 | expP1 := []string{"_/Namespace/_/test-basic"} 30 | assert.ElementsMatch(t, expP1, idsPrio[0], nil) 31 | 32 | expP2 := []string{"apps/Deployment/test-basic/test", "networking.k8s.io/Ingress/test-basic/test", "_/Service/test-basic/test"} 33 | assert.ElementsMatch(t, expP2, idsPrio[1], nil) 34 | 35 | expP3 := []string{} 36 | assert.ElementsMatch(t, expP3, idsPrio[2], nil) 37 | } 38 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/_example_app/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | creationTimestamp: null 5 | labels: 6 | app: test 7 | name: test 8 | spec: 9 | replicas: 1 10 | selector: 11 | matchLabels: 12 | app: test 13 | strategy: {} 14 | template: 15 | metadata: 16 | creationTimestamp: null 17 | labels: 18 | app: test 19 | spec: 20 | containers: 21 | - image: nginx 22 | name: nginx 23 | resources: {} 24 | status: {} 25 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/_example_app/ingress.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: networking.k8s.io/v1 2 | kind: Ingress 3 | metadata: 4 | name: test 5 | annotations: 6 | nginx.ingress.kubernetes.io/rewrite-target: / 7 | spec: 8 | rules: 9 | - http: 10 | paths: 11 | - path: /testpath 12 | pathType: Prefix 13 | backend: 14 | service: 15 | name: test 16 | port: 17 | number: 80 -------------------------------------------------------------------------------- /kustomize/test_kustomizations/_example_app/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | resources: 5 | - deployment.yaml 6 | - ingress.yaml 7 | - service.yaml 8 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/_example_app/service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | creationTimestamp: null 5 | labels: 6 | app: test 7 | name: test 8 | spec: 9 | ports: 10 | - name: http 11 | port: 80 12 | protocol: TCP 13 | targetPort: 80 14 | selector: 15 | app: test 16 | type: ClusterIP 17 | status: 18 | loadBalancer: {} 19 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/_test_files/cmGenerator.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: builtin 2 | kind: ConfigMapGenerator 3 | metadata: 4 | name: testcm -------------------------------------------------------------------------------- /kustomize/test_kustomizations/_test_files/deployment_patch_env.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | labels: 5 | app: test 6 | name: test 7 | spec: 8 | template: 9 | spec: 10 | containers: 11 | - name: nginx 12 | env: 13 | - name: TESTENV 14 | value: "true" 15 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/_test_files/properties.env: -------------------------------------------------------------------------------- 1 | ENV1=VALUE1 2 | ENV2=VALUE2 3 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/basic/initial/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-basic 5 | 6 | resources: 7 | - namespace.yaml 8 | - ../../_example_app 9 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/basic/initial/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: test-basic 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/basic/modified/deployment2.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | creationTimestamp: null 5 | labels: 6 | app: test2 7 | name: test2 8 | namespace: test-basic 9 | spec: 10 | replicas: 1 11 | selector: 12 | matchLabels: 13 | app: test2 14 | strategy: {} 15 | template: 16 | metadata: 17 | creationTimestamp: null 18 | labels: 19 | app: test2 20 | spec: 21 | containers: 22 | - image: nginx 23 | name: nginx 24 | resources: {} 25 | status: {} 26 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/basic/modified/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | resources: 5 | - ../initial 6 | - deployment2.yaml 7 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/component/Kustomization: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1alpha1 2 | kind: Component 3 | 4 | configMapGenerator: 5 | - name: from-component 6 | literals: [] 7 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/crd/initial/co.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: test.example.com/v1alpha1 2 | kind: Namespacedcrd 3 | metadata: 4 | name: namespacedco 5 | namespace: test-crd 6 | spec: 7 | test-key: test-value-initial 8 | --- 9 | apiVersion: test.example.com/v1alpha1 10 | kind: Clusteredcrd 11 | metadata: 12 | name: clusteredco 13 | spec: 14 | test-key: test-value-initial 15 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/crd/initial/crd.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apiextensions.k8s.io/v1 2 | kind: CustomResourceDefinition 3 | metadata: 4 | name: namespacedcrds.test.example.com 5 | spec: 6 | group: test.example.com 7 | names: 8 | kind: Namespacedcrd 9 | plural: namespacedcrds 10 | shortNames: 11 | - ncrds 12 | scope: Namespaced 13 | versions: 14 | - name: v1alpha1 15 | served: true 16 | storage: true 17 | schema: 18 | openAPIV3Schema: 19 | type: object 20 | properties: 21 | spec: 22 | type: object 23 | properties: 24 | test-key: 25 | type: string 26 | --- 27 | apiVersion: apiextensions.k8s.io/v1 28 | kind: CustomResourceDefinition 29 | metadata: 30 | name: clusteredcrds.test.example.com 31 | spec: 32 | group: test.example.com 33 | names: 34 | kind: Clusteredcrd 35 | plural: clusteredcrds 36 | shortNames: 37 | - ccrds 38 | scope: Cluster 39 | versions: 40 | - name: v1alpha1 41 | served: true 42 | storage: true 43 | schema: 44 | openAPIV3Schema: 45 | type: object 46 | properties: 47 | spec: 48 | type: object 49 | properties: 50 | test-key: 51 | type: string 52 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/crd/initial/kustomization.yaml: -------------------------------------------------------------------------------- 1 | resources: 2 | - namespace.yaml 3 | - crd.yaml 4 | - co.yaml 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/crd/initial/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: test-crd 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/crd/modified/co-patch-clustered.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: test.example.com/v1alpha1 2 | kind: Clusteredcrd 3 | metadata: 4 | name: clusteredco 5 | spec: 6 | test-key: test-value-modified 7 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/crd/modified/co-patch-namespaced.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: test.example.com/v1alpha1 2 | kind: Namespacedcrd 3 | metadata: 4 | name: namespacedco 5 | namespace: test-crd 6 | spec: 7 | test-key: test-value-modified 8 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/crd/modified/kustomization.yaml: -------------------------------------------------------------------------------- 1 | resources: 2 | - ../initial 3 | 4 | patches: 5 | - path: co-patch-clustered.yaml 6 | - path: co-patch-namespaced.yaml 7 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/fail_namespace_not_allowed/invalid_cluster_role_binding.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: rbac.authorization.k8s.io/v1 2 | kind: ClusterRoleBinding 3 | metadata: 4 | name: invalid 5 | # invalid not namespace scoped 6 | namespace: default 7 | subjects: 8 | - kind: Group 9 | name: admins 10 | apiGroup: rbac.authorization.k8s.io 11 | roleRef: 12 | kind: ClusterRole 13 | name: admin 14 | apiGroup: rbac.authorization.k8s.io 15 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/fail_namespace_not_allowed/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | resources: 5 | - invalid_cluster_role_binding.yaml 6 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/fail_namespace_required/invalid_role_binding.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: rbac.authorization.k8s.io/v1 2 | kind: RoleBinding 3 | metadata: 4 | name: invalid 5 | # invalid namespace scoped but no namespace 6 | subjects: 7 | - kind: Group 8 | name: admins 9 | apiGroup: rbac.authorization.k8s.io 10 | roleRef: 11 | kind: ClusterRole 12 | name: admin 13 | apiGroup: rbac.authorization.k8s.io 14 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/fail_namespace_required/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | resources: 5 | - invalid_role_binding.yaml 6 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/fail_plan_invalid/invalid_cluster_role_binding.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: rbac.authorization.k8s.io/v1 2 | kind: ClusterRoleBinding 3 | metadata: 4 | name: invalid 5 | subjects: 6 | - kind: Group 7 | name: admins 8 | apiGroup: rbac.authorization.k8s.io 9 | roleRef: 10 | # invalid roleRef to fail test - roleRef should reference a ClusterRole, not a Role 11 | kind: Role 12 | name: secret-reader 13 | apiGroup: rbac.authorization.k8s.io 14 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/fail_plan_invalid/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | resources: 5 | - invalid_cluster_role_binding.yaml 6 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/alt-values.yaml: -------------------------------------------------------------------------------- 1 | # Alternate values for test-basic 2 | # This is a YAML-formatted file. 3 | # Declare variables to be passed into your templates. 4 | 5 | replicaCount: 2 6 | 7 | image: 8 | repository: my-nginx 9 | # Overrides the image tag whose default is the chart appVersion. 10 | tag: "6.0.10" 11 | 12 | nginx: 13 | port: 443 14 | 15 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/charts/test-basic/Chart.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v2 2 | description: A Simple Helm chart 3 | name: test-basic 4 | version: 0.0.1 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/charts/test-basic/crds/crontabs.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apiextensions.k8s.io/v1 2 | kind: CustomResourceDefinition 3 | metadata: 4 | # name must match the spec fields below, and be in the form: . 5 | name: crontabs.stable.example.com 6 | spec: 7 | # group name to use for REST API: /apis// 8 | group: stable.example.com 9 | # list of versions supported by this CustomResourceDefinition 10 | versions: 11 | - name: v1 12 | # Each version can be enabled/disabled by Served flag. 13 | served: true 14 | # One and only one version must be marked as the storage version. 15 | storage: true 16 | schema: 17 | openAPIV3Schema: 18 | type: object 19 | properties: 20 | spec: 21 | type: object 22 | properties: 23 | cronSpec: 24 | type: string 25 | image: 26 | type: string 27 | replicas: 28 | type: integer 29 | # either Namespaced or Cluster 30 | scope: Namespaced 31 | names: 32 | # plural name to be used in the URL: /apis/// 33 | plural: crontabs 34 | # singular name to be used as an alias on the CLI and for display 35 | singular: crontab 36 | # kind is normally the CamelCased singular type. Your resource manifests use this. 37 | kind: CronTab 38 | # shortNames allow shorter string to match your resource on the CLI 39 | shortNames: 40 | - ct 41 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/charts/test-basic/templates/_helpers.tpl: -------------------------------------------------------------------------------- 1 | {{/* 2 | Expand the name of the chart. Set the chart name to nginx by default 3 | */}} 4 | {{- define "test-basic.name" -}} 5 | {{- default "nginx" }} 6 | {{- end }} 7 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/charts/test-basic/templates/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | creationTimestamp: null 5 | labels: 6 | app: {{ include "test-basic.name" . }} 7 | name: {{ include "test-basic.name" . }} 8 | spec: 9 | replicas: {{ .Values.replicaCount }} 10 | selector: 11 | matchLabels: 12 | app: {{ include "test-basic.name" . }} 13 | strategy: {} 14 | template: 15 | metadata: 16 | creationTimestamp: null 17 | labels: 18 | app: {{ include "test-basic.name" . }} 19 | spec: 20 | containers: 21 | - image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" 22 | name : {{ .Chart.Name }} 23 | resources: {} 24 | status: {} 25 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/charts/test-basic/templates/ingress.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: networking.k8s.io/v1beta1 2 | kind: Ingress 3 | metadata: 4 | name: {{ include "test-basic.name" . }} 5 | annotations: 6 | nginx.ingress.kubernetes.io/rewrite-target: / 7 | spec: 8 | rules: 9 | - http: 10 | paths: 11 | - path: /testpath 12 | backend: 13 | serviceName: {{ include "test-basic.name" . }} 14 | servicePort: {{ .Values.nginx.port }} 15 | 16 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/charts/test-basic/templates/service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | creationTimestamp: null 5 | labels: 6 | app: {{ include "test-basic.name" . }} 7 | name: {{ include "test-basic.name" . }} 8 | spec: 9 | ports: 10 | - name: http 11 | port: {{ .Values.nginx.port }} 12 | protocol: TCP 13 | targetPort: {{ .Values.nginx.port }} 14 | selector: 15 | app: {{ include "test-basic.name" . }} 16 | type: ClusterIP 17 | status: 18 | loadBalancer: {} 19 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/charts/test-basic/templates/tests/test-connection.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: "{{ include "test-basic.name" . }}-test-connection" 5 | annotations: 6 | "helm.sh/hook": test 7 | spec: 8 | containers: 9 | - name: wget 10 | image: busybox 11 | command: ['wget'] 12 | args: ['{{ include "test-basic.name" . }}:{{ .Values.nginx.port }}/testpath'] 13 | restartPolicy: Never 14 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/charts/test-basic/values.yaml: -------------------------------------------------------------------------------- 1 | # Default values for test-basic 2 | # This is a YAML-formatted file. 3 | # Declare variables to be passed into your templates. 4 | 5 | replicaCount: 1 6 | 7 | image: 8 | repository: nginx 9 | # Overrides the image tag whose default is the chart appVersion. 10 | tag: "6.0.10" 11 | 12 | nginx: 13 | port: 80 14 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/charts/test-capabilities/Chart.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v2 2 | description: A Simple Helm chart to test capabilitie set by the user 3 | name: test-capabilities 4 | version: 0.0.1 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/charts/test-capabilities/templates/_helpers.tpl: -------------------------------------------------------------------------------- 1 | {{/* 2 | Expand the name of the chart. Set the chart name to nginx by default 3 | */}} 4 | {{- define "test-capabilities.name" -}} 5 | {{- .Release.Name | default "capabilities" }} 6 | {{- end }} 7 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/charts/test-capabilities/templates/configmap.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: v1 3 | kind: ConfigMap 4 | metadata: 5 | name: default-configmap 6 | labels: 7 | app: {{ include "test-capabilities.name" . }} 8 | name: {{ include "test-capabilities.name" . }} 9 | data: 10 | should: "always exist" 11 | --- 12 | {{ if eq .Capabilities.KubeVersion.Version "v1.42.0" }} 13 | apiVersion: v1 14 | kind: ConfigMap 15 | metadata: 16 | name: kubeversion-configmap 17 | labels: 18 | app: {{ include "test-capabilities.name" . }} 19 | name: {{ include "test-capabilities.name" . }} 20 | data: 21 | should: "only when kubeversion is equals v1.42.0" 22 | {{- end }} 23 | --- 24 | {{ if $.Capabilities.APIVersions.Has "foo.bar/v1" }} 25 | apiVersion: v1 26 | kind: ConfigMap 27 | metadata: 28 | name: apiversions-configmap 29 | labels: 30 | app: {{ include "test-capabilities.name" . }} 31 | name: {{ include "test-capabilities.name" . }} 32 | data: 33 | should: "only when a the fake apiVersion is set" 34 | {{- end }} -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/charts/test-capabilities/values.yaml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kbst/terraform-provider-kustomization/adf37d2cbfc6f5fc6f3bff008397b98939ab3915/kustomize/test_kustomizations/helm/initial/charts/test-capabilities/values.yaml -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/charts/test-releasename/Chart.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v2 2 | description: A Simple Helm chart 3 | name: test-releasename 4 | version: 0.0.1 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/charts/test-releasename/templates/_helpers.tpl: -------------------------------------------------------------------------------- 1 | {{/* 2 | Expand the name of the chart. Set the chart name to nginx by default 3 | */}} 4 | {{- define "test-basic.name" -}} 5 | {{- .Release.Name | default "nginx" }} 6 | {{- end }} 7 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/charts/test-releasename/templates/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | creationTimestamp: null 5 | labels: 6 | app: {{ include "test-basic.name" . }} 7 | name: {{ include "test-basic.name" . }} 8 | spec: 9 | replicas: {{ .Values.replicaCount }} 10 | selector: 11 | matchLabels: 12 | app: {{ include "test-basic.name" . }} 13 | strategy: {} 14 | template: 15 | metadata: 16 | creationTimestamp: null 17 | labels: 18 | app: {{ include "test-basic.name" . }} 19 | spec: 20 | containers: 21 | - image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" 22 | name : {{ .Chart.Name }} 23 | resources: {} 24 | status: {} 25 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/charts/test-releasename/templates/ingress.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: networking.k8s.io/v1beta1 2 | kind: Ingress 3 | metadata: 4 | name: {{ include "test-basic.name" . }} 5 | annotations: 6 | nginx.ingress.kubernetes.io/rewrite-target: / 7 | spec: 8 | rules: 9 | - http: 10 | paths: 11 | - path: /testpath 12 | backend: 13 | serviceName: {{ include "test-basic.name" . }} 14 | servicePort: {{ .Values.nginx.port }} 15 | 16 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/charts/test-releasename/templates/service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | creationTimestamp: null 5 | labels: 6 | app: {{ include "test-basic.name" . }} 7 | name: {{ include "test-basic.name" . }} 8 | spec: 9 | ports: 10 | - name: http 11 | port: {{ .Values.nginx.port }} 12 | protocol: TCP 13 | targetPort: {{ .Values.nginx.port }} 14 | selector: 15 | app: {{ include "test-basic.name" . }} 16 | type: ClusterIP 17 | status: 18 | loadBalancer: {} 19 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/charts/test-releasename/values.yaml: -------------------------------------------------------------------------------- 1 | # Default values for test-basic 2 | # This is a YAML-formatted file. 3 | # Declare variables to be passed into your templates. 4 | 5 | replicaCount: 1 6 | 7 | image: 8 | repository: nginx 9 | # Overrides the image tag whose default is the chart appVersion. 10 | tag: "6.0.10" 11 | 12 | nginx: 13 | port: 80 14 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-basic 5 | 6 | resources: 7 | - namespace.yaml 8 | 9 | helmCharts: 10 | - name: test-basic 11 | version: 0.0.1 12 | namespace: not-used 13 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/merge-values.yaml: -------------------------------------------------------------------------------- 1 | # Alternate values for test-basic 2 | # This is a YAML-formatted file. 3 | # Declare variables to be passed into your templates. 4 | image: 5 | repository: my-nginx 6 | # Overrides the image tag whose default is the chart appVersion. 7 | tag: "6.0.10" 8 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/helm/initial/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: test-basic 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/nowait/initial/daemonset.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: DaemonSet 3 | metadata: 4 | labels: 5 | app: test 6 | name: test 7 | spec: 8 | selector: 9 | matchLabels: 10 | app: test 11 | template: 12 | metadata: 13 | labels: 14 | app: test 15 | spec: 16 | containers: 17 | - image: nginx 18 | name: nginx 19 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/nowait/initial/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-nowait 5 | 6 | resources: 7 | - namespace.yaml 8 | - daemonset.yaml 9 | - statefulset.yaml 10 | - ../../_example_app 11 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/nowait/initial/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: test-nowait 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/nowait/initial/statefulset.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: StatefulSet 3 | metadata: 4 | labels: 5 | app: test 6 | name: test 7 | spec: 8 | replicas: 1 9 | selector: 10 | matchLabels: 11 | app: test 12 | template: 13 | metadata: 14 | labels: 15 | app: test 16 | spec: 17 | containers: 18 | - image: nginx 19 | name: nginx 20 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/nowait/modified/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | resources: 5 | - ../initial 6 | 7 | patches: 8 | - target: 9 | kind: Deployment 10 | name: test 11 | patch: | 12 | - op: add 13 | path: /spec/template/metadata/annotations 14 | value: 15 | new: this will cause a redeploy 16 | - target: 17 | kind: DaemonSet 18 | name: test 19 | patch: | 20 | - op: add 21 | path: /spec/template/metadata/annotations 22 | value: 23 | new: this will cause a redeploy 24 | - target: 25 | kind: StatefulSet 26 | name: test 27 | patch: | 28 | - op: add 29 | path: /spec/template/metadata/annotations 30 | value: 31 | new: this will cause a redeploy 32 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/replacements/configmap.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ConfigMap 3 | metadata: 4 | name: replacement-source 5 | namespace: test-replacements 6 | data: 7 | replace1: this-is-replace1 8 | replace2: this-is-replace2 9 | REPLACE_ME: this should stay untouched 10 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/replacements/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-replacements 5 | 6 | resources: 7 | - namespace.yaml 8 | - configmap.yaml 9 | - target1.yaml 10 | - target2.yaml 11 | - target3.yaml 12 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/replacements/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: test-replacements 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/replacements/replacements.yaml: -------------------------------------------------------------------------------- 1 | source: 2 | kind: "ConfigMap" 3 | name: "replacement-source" 4 | fieldPath: "data.replace1" 5 | targets: 6 | - select: 7 | kind: Pod 8 | reject: 9 | - name: replacement-pod-2 10 | fieldPaths: 11 | - "spec.containers.[name=modify-me].env.[name=MODIFY_ME].value" 12 | - select: 13 | kind: ConfigMap 14 | name: replacement-target 15 | fieldPaths: 16 | - data.REPLACE_ME 17 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/replacements/target1.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: replacement-pod 5 | namespace: test-replacements 6 | spec: 7 | containers: 8 | - name: modify-me 9 | image: postgres:latest 10 | env: 11 | - name: MODIFY_ME 12 | value: should not matter 13 | - name: LEAVE_ME_ALONE 14 | value: this should stay untouched 15 | - name: leave-me-alone 16 | image: nginx:latest 17 | env: 18 | - name: UNMODIFIED 19 | value: still the same 20 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/replacements/target2.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: replacement-pod-2 5 | namespace: test-replacements 6 | spec: 7 | containers: 8 | - name: modify-me 9 | image: postgres:latest 10 | env: 11 | - name: MODIFY_ME 12 | value: this should be ignored by reject rule 13 | - name: LEAVE_ME_ALONE 14 | value: this should stay untouched 15 | - name: leave-me-alone 16 | image: nginx:latest 17 | env: 18 | - name: UNMODIFIED 19 | value: still the same 20 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/replacements/target3.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ConfigMap 3 | metadata: 4 | name: replacement-target 5 | namespace: test-replacements 6 | data: 7 | REPLACE_ME: this should change 8 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/secret_service_account_token/Kustomization: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-secret-sa-token 5 | 6 | resources: 7 | - namespace.yaml 8 | - secret_default.yaml 9 | - secret_sa_token.yaml 10 | - service_account.yaml 11 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/secret_service_account_token/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: test-secret-sa-token 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/secret_service_account_token/secret_default.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Secret 3 | metadata: 4 | name: test 5 | namespace: test-secret-sa-token 6 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/secret_service_account_token/secret_sa_token.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Secret 3 | metadata: 4 | name: test-sa-token 5 | namespace: test-secret-sa-token 6 | annotations: 7 | kubernetes.io/service-account.name: test-sa 8 | type: kubernetes.io/service-account-token 9 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/secret_service_account_token/service_account.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ServiceAccount 3 | metadata: 4 | name: test-sa 5 | namespace: test-secret-sa-token 6 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/transformer_configs/initial/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-transformer-config 5 | 6 | resources: 7 | - namespace.yaml 8 | - ../../_example_app 9 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/transformer_configs/initial/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: test-transformer-config 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/transformer_configs/modified/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | resources: 5 | - ../initial 6 | 7 | transformers: 8 | - label.yaml 9 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/transformer_configs/modified/label.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: builtin 2 | kind: LabelTransformer 3 | metadata: 4 | name: labels 5 | labels: 6 | test.example.com/test-label: test-value 7 | fieldSpecs: 8 | - path: metadata/labels 9 | create: true 10 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_inplace/initial/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-update-inplace 5 | 6 | resources: 7 | - namespace.yaml 8 | - ../../_example_app 9 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_inplace/initial/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: test-update-inplace 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_inplace/modified/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | resources: 5 | - ../initial 6 | 7 | commonAnnotations: 8 | test_annotation: added 9 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_merge_fallback/initial/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-update-merge-fallback 5 | 6 | resources: 7 | - namespace.yaml 8 | - ../../_example_app 9 | 10 | patches: 11 | - path: patch_deployment_env.yaml 12 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_merge_fallback/initial/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: test-update-merge-fallback 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_merge_fallback/initial/patch_deployment_env.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: test 5 | spec: 6 | template: 7 | spec: 8 | containers: 9 | - name: nginx 10 | env: 11 | - name: TEST_ENV 12 | value: "1" 13 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_merge_fallback/modified/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-update-merge-fallback 5 | 6 | configMapGenerator: 7 | - name: test-envfrom 8 | literals: 9 | - "env=KEY1=VALUE1\nKEY2=VALUE2\n" 10 | 11 | resources: 12 | - namespace.yaml 13 | - ../../_example_app 14 | 15 | patches: 16 | - path: patch_deployment_envfrom.yaml 17 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_merge_fallback/modified/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: test-update-merge-fallback 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_merge_fallback/modified/patch_deployment_envfrom.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: test 5 | spec: 6 | template: 7 | spec: 8 | containers: 9 | - name: nginx 10 | env: 11 | - name: TEST_ENV 12 | valueFrom: 13 | configMapKeyRef: 14 | name: test-envfrom 15 | key: env 16 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate/initial/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-update-recreate 5 | 6 | resources: 7 | - namespace.yaml 8 | - ../../_example_app 9 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate/initial/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: test-update-recreate 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate/modified/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | resources: 5 | - ../initial 6 | 7 | patches: 8 | - path: patch_selector.yaml 9 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate/modified/patch_selector.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: test 5 | spec: 6 | selector: 7 | matchLabels: 8 | app: test 9 | test-label: added 10 | template: 11 | metadata: 12 | labels: 13 | app: test 14 | test-label: added 15 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate_name_or_namespace_change/initial/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-update-recreate-name-or-namespace-change 5 | 6 | resources: 7 | - namespace.yaml 8 | 9 | configMapGenerator: 10 | - name: test 11 | options: 12 | disableNameSuffixHash: true 13 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate_name_or_namespace_change/initial/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: test-update-recreate-name-or-namespace-change 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate_name_or_namespace_change/modified/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-update-recreate-name-or-namespace-change-modified 5 | 6 | resources: 7 | - ../initial 8 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate_roleref/initial/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-update-recreate-roleref 5 | 6 | resources: 7 | - namespace.yaml 8 | - rbac.yaml 9 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate_roleref/initial/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: test-update-recreate-roleref 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate_roleref/initial/rbac.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: rbac.authorization.k8s.io/v1 2 | kind: Role 3 | metadata: 4 | namespace: test-update-recreate-roleref 5 | name: test-initial 6 | rules: 7 | - apiGroups: [""] 8 | resources: ["configmaps"] 9 | verbs: ["get", "watch", "list"] 10 | --- 11 | apiVersion: rbac.authorization.k8s.io/v1 12 | kind: RoleBinding 13 | metadata: 14 | name: test 15 | namespace: test-update-recreate-roleref 16 | subjects: 17 | - kind: ServiceAccount 18 | name: default 19 | namespace: test-update-recreate-roleref 20 | roleRef: 21 | kind: Role #this must be Role or ClusterRole 22 | name: test-initial 23 | apiGroup: rbac.authorization.k8s.io 24 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate_roleref/modified/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-update-recreate-roleref 5 | 6 | resources: 7 | - ../initial 8 | 9 | patches: 10 | - patch: | 11 | - op: replace 12 | path: /metadata/name 13 | value: test-modified 14 | target: 15 | group: "rbac.authorization.k8s.io" 16 | version: v1 17 | kind: Role 18 | name: test-initial 19 | - patch: | 20 | - op: replace 21 | path: /roleRef/name 22 | value: test-modified 23 | target: 24 | group: "rbac.authorization.k8s.io" 25 | version: v1 26 | kind: RoleBinding 27 | name: test 28 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate_statefulset/initial/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-update-recreate-statefulset 5 | 6 | resources: 7 | - namespace.yaml 8 | - statefulset.yaml 9 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate_statefulset/initial/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: test-update-recreate-statefulset 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate_statefulset/initial/statefulset.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: StatefulSet 3 | metadata: 4 | name: test 5 | spec: 6 | selector: 7 | matchLabels: 8 | app: nginx 9 | serviceName: "nginx" 10 | replicas: 1 11 | template: 12 | metadata: 13 | labels: 14 | app: nginx 15 | spec: 16 | terminationGracePeriodSeconds: 10 17 | containers: 18 | - name: nginx 19 | image: nginx 20 | ports: 21 | - containerPort: 80 22 | name: web 23 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate_statefulset/modified/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-update-recreate-statefulset 5 | 6 | resources: 7 | - ../initial 8 | 9 | commonLabels: 10 | test-label: "triggers-labelSelector-change" 11 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate_storage_class/initial/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | resources: 5 | - storage-class-parameters.yaml 6 | - storage-class-provisioner.yaml -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate_storage_class/initial/storage-class-parameters.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: storage.k8s.io/v1 2 | kind: StorageClass 3 | metadata: 4 | name: local-storage-parameters 5 | provisioner: kubernetes.io/no-provisioner 6 | volumeBindingMode: WaitForFirstConsumer 7 | parameters: 8 | test: test 9 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate_storage_class/initial/storage-class-provisioner.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: storage.k8s.io/v1 2 | kind: StorageClass 3 | metadata: 4 | name: local-storage-provisioner 5 | provisioner: kubernetes.io/no-provisioner 6 | volumeBindingMode: WaitForFirstConsumer 7 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/update_recreate_storage_class/modified/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | resources: 5 | - ../initial 6 | 7 | patches: 8 | - patch: | 9 | - op: replace 10 | path: /parameters/test 11 | value: test2 12 | target: 13 | group: "storage.k8s.io" 14 | version: v1 15 | kind: StorageClass 16 | name: local-storage-parameters 17 | - patch: | 18 | - op: replace 19 | path: /provisioner 20 | value: example.com/external-nfs 21 | target: 22 | group: "storage.k8s.io" 23 | version: v1 24 | kind: StorageClass 25 | name: local-storage-provisioner 26 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/upgrade_api_version/initial/co.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: test.example.com/v1alpha1 2 | kind: Namespacedcrd 3 | metadata: 4 | name: namespacedco 5 | namespace: test-upgrade-api-version 6 | spec: 7 | test-key: test-value-initial 8 | --- 9 | apiVersion: test.example.com/v1alpha1 10 | kind: Clusteredcrd 11 | metadata: 12 | name: clusteredco 13 | spec: 14 | test-key: test-value-initial 15 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/upgrade_api_version/initial/crd.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apiextensions.k8s.io/v1 2 | kind: CustomResourceDefinition 3 | metadata: 4 | name: namespacedcrds.test.example.com 5 | spec: 6 | group: test.example.com 7 | names: 8 | kind: Namespacedcrd 9 | plural: namespacedcrds 10 | shortNames: 11 | - ncrds 12 | scope: Namespaced 13 | versions: 14 | - name: v1alpha1 15 | served: true 16 | storage: false 17 | schema: 18 | openAPIV3Schema: 19 | type: object 20 | properties: 21 | spec: 22 | type: object 23 | properties: 24 | test-key: 25 | type: string 26 | - name: v1beta1 27 | served: true 28 | storage: true 29 | schema: 30 | openAPIV3Schema: 31 | type: object 32 | properties: 33 | spec: 34 | type: object 35 | properties: 36 | test-key: 37 | type: string 38 | --- 39 | apiVersion: apiextensions.k8s.io/v1 40 | kind: CustomResourceDefinition 41 | metadata: 42 | name: clusteredcrds.test.example.com 43 | spec: 44 | group: test.example.com 45 | names: 46 | kind: Clusteredcrd 47 | plural: clusteredcrds 48 | shortNames: 49 | - ccrds 50 | scope: Cluster 51 | versions: 52 | - name: v1alpha1 53 | served: true 54 | storage: false 55 | schema: 56 | openAPIV3Schema: 57 | type: object 58 | properties: 59 | spec: 60 | type: object 61 | properties: 62 | test-key: 63 | type: string 64 | - name: v1beta1 65 | served: true 66 | storage: true 67 | schema: 68 | openAPIV3Schema: 69 | type: object 70 | properties: 71 | spec: 72 | type: object 73 | properties: 74 | test-key: 75 | type: string 76 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/upgrade_api_version/initial/kustomization.yaml: -------------------------------------------------------------------------------- 1 | resources: 2 | - namespace.yaml 3 | - crd.yaml 4 | - co.yaml 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/upgrade_api_version/initial/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: test-upgrade-api-version 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/upgrade_api_version/modified/kustomization.yaml: -------------------------------------------------------------------------------- 1 | resources: 2 | - ../initial 3 | 4 | patches: 5 | - patch: | 6 | - op: replace 7 | path: /apiVersion 8 | value: test.example.com/v1beta1 9 | target: 10 | group: test.example.com 11 | version: v1alpha1 12 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/wait-change/initial/daemonset.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: DaemonSet 3 | metadata: 4 | labels: 5 | app: test 6 | name: test 7 | spec: 8 | selector: 9 | matchLabels: 10 | app: test 11 | template: 12 | metadata: 13 | labels: 14 | app: test 15 | spec: 16 | containers: 17 | - image: nginx 18 | name: nginx 19 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/wait-change/initial/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-wait-change 5 | 6 | resources: 7 | - namespace.yaml 8 | - daemonset.yaml 9 | - statefulset.yaml 10 | - ../../_example_app 11 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/wait-change/initial/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: test-wait-change 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/wait-change/initial/statefulset.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: StatefulSet 3 | metadata: 4 | labels: 5 | app: test 6 | name: test 7 | spec: 8 | replicas: 1 9 | selector: 10 | matchLabels: 11 | app: test 12 | template: 13 | metadata: 14 | labels: 15 | app: test 16 | spec: 17 | containers: 18 | - image: nginx 19 | name: nginx 20 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/wait-fail/initial/daemonset.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: DaemonSet 3 | metadata: 4 | labels: 5 | app: test 6 | name: test 7 | spec: 8 | selector: 9 | matchLabels: 10 | app: test 11 | template: 12 | metadata: 13 | labels: 14 | app: test 15 | spec: 16 | containers: 17 | - image: nginx 18 | name: nginx 19 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/wait-fail/initial/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-wait-fail 5 | 6 | resources: 7 | - namespace.yaml 8 | - daemonset.yaml 9 | - statefulset.yaml 10 | - ../../_example_app 11 | 12 | images: 13 | - name: nginx 14 | newName: doesnotexist/definitelydoesntexist 15 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/wait-fail/initial/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: test-wait-fail 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/wait-fail/initial/statefulset.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: StatefulSet 3 | metadata: 4 | labels: 5 | app: test 6 | name: test 7 | spec: 8 | replicas: 1 9 | selector: 10 | matchLabels: 11 | app: test 12 | template: 13 | metadata: 14 | labels: 15 | app: test 16 | spec: 17 | containers: 18 | - image: nginx 19 | name: nginx 20 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/wait/initial/daemonset.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: DaemonSet 3 | metadata: 4 | labels: 5 | app: test 6 | name: test 7 | spec: 8 | selector: 9 | matchLabels: 10 | app: test 11 | template: 12 | metadata: 13 | labels: 14 | app: test 15 | spec: 16 | containers: 17 | - image: nginx 18 | name: nginx 19 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/wait/initial/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | namespace: test-wait 5 | 6 | resources: 7 | - namespace.yaml 8 | - daemonset.yaml 9 | - statefulset.yaml 10 | - ../../_example_app 11 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/wait/initial/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: test-wait 5 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/wait/initial/statefulset.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: StatefulSet 3 | metadata: 4 | labels: 5 | app: test 6 | name: test 7 | spec: 8 | replicas: 1 9 | selector: 10 | matchLabels: 11 | app: test 12 | template: 13 | metadata: 14 | labels: 15 | app: test 16 | spec: 17 | containers: 18 | - image: nginx 19 | name: nginx 20 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/wait/modified/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | resources: 5 | - ../initial 6 | 7 | patches: 8 | - target: 9 | kind: Deployment 10 | name: test 11 | patch: | 12 | - op: add 13 | path: /spec/template/metadata/annotations 14 | value: 15 | new: this will cause a redeploy 16 | - target: 17 | kind: StatefulSet 18 | name: test 19 | patch: | 20 | - op: add 21 | path: /spec/template/metadata/annotations 22 | value: 23 | new: this will cause a redeploy 24 | - target: 25 | kind: DaemonSet 26 | name: test 27 | patch: | 28 | - op: add 29 | path: /spec/template/metadata/annotations 30 | value: 31 | new: this will cause a redeploy 32 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/webhook/initial/kustomization.yaml: -------------------------------------------------------------------------------- 1 | resources: 2 | - webhook.yaml 3 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/webhook/initial/webhook.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: admissionregistration.k8s.io/v1 2 | kind: ValidatingWebhookConfiguration 3 | metadata: 4 | name: "pod-policy.example.com" 5 | webhooks: 6 | - name: "pod-policy.example.com" 7 | rules: 8 | - apiGroups: [""] 9 | apiVersions: ["v1"] 10 | operations: ["CREATE"] 11 | resources: ["pods"] 12 | scope: "Namespaced" 13 | clientConfig: 14 | service: 15 | namespace: "example-namespace" 16 | name: "example-service" 17 | admissionReviewVersions: ["v1", "v1beta1"] 18 | sideEffects: None 19 | timeoutSeconds: 5 20 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/webhook/modified/kustomization.yaml: -------------------------------------------------------------------------------- 1 | resources: 2 | - ../initial 3 | 4 | patches: 5 | - path: webhook-patch.yaml 6 | -------------------------------------------------------------------------------- /kustomize/test_kustomizations/webhook/modified/webhook-patch.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: admissionregistration.k8s.io/v1 2 | kind: ValidatingWebhookConfiguration 3 | metadata: 4 | name: "pod-policy.example.com" 5 | webhooks: 6 | - name: "pod-policy.example.com" 7 | rules: 8 | - apiGroups: [""] 9 | apiVersions: ["v1"] 10 | operations: ["DELETE"] 11 | resources: ["pods"] 12 | scope: "Namespaced" 13 | -------------------------------------------------------------------------------- /kustomize/util.go: -------------------------------------------------------------------------------- 1 | package kustomize 2 | 3 | import ( 4 | "bytes" 5 | "compress/gzip" 6 | "encoding/base64" 7 | "fmt" 8 | "io" 9 | "log" 10 | "runtime" 11 | "strings" 12 | 13 | k8scorev1 "k8s.io/api/core/v1" 14 | k8svalidation "k8s.io/apimachinery/pkg/api/validation" 15 | k8sunstructured "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" 16 | k8sruntime "k8s.io/apimachinery/pkg/runtime" 17 | k8sschema "k8s.io/apimachinery/pkg/runtime/schema" 18 | k8stypes "k8s.io/apimachinery/pkg/types" 19 | 20 | "k8s.io/apimachinery/pkg/util/jsonmergepatch" 21 | "k8s.io/apimachinery/pkg/util/mergepatch" 22 | "k8s.io/apimachinery/pkg/util/strategicpatch" 23 | "k8s.io/kubectl/pkg/scheme" 24 | ) 25 | 26 | const lastAppliedConfigAnnotation = k8scorev1.LastAppliedConfigAnnotation 27 | const gzipLastAppliedConfigAnnotation = "kustomization.kubestack.com/last-applied-config-gzip" 28 | 29 | func setLastAppliedConfig(km *kManifest, gzipLastAppliedConfig bool) { 30 | annotations := km.resource.GetAnnotations() 31 | if len(annotations) == 0 { 32 | annotations = make(map[string]string) 33 | } 34 | 35 | annotations[lastAppliedConfigAnnotation] = string(km.json) 36 | 37 | if gzipLastAppliedConfig { 38 | needsGzip := false 39 | sErr := k8svalidation.ValidateAnnotationsSize(annotations) 40 | if sErr != nil { 41 | needsGzip = true 42 | } 43 | 44 | if needsGzip { 45 | var buf bytes.Buffer 46 | zw := gzip.NewWriter(&buf) 47 | 48 | _, err1 := zw.Write([]byte(km.json)) 49 | 50 | err2 := zw.Close() 51 | 52 | if err1 == nil && err2 == nil { 53 | annotations[gzipLastAppliedConfigAnnotation] = base64.StdEncoding.EncodeToString(buf.Bytes()) 54 | delete(annotations, lastAppliedConfigAnnotation) 55 | } 56 | } 57 | } 58 | 59 | km.resource.SetAnnotations(annotations) 60 | km.json, _ = km.resource.MarshalJSON() 61 | } 62 | 63 | func getLastAppliedConfig(u *k8sunstructured.Unstructured, gzipLastAppliedConfig bool) (lac string) { 64 | annotations := u.GetAnnotations() 65 | 66 | lac = u.GetAnnotations()[lastAppliedConfigAnnotation] 67 | 68 | if gzipLastAppliedConfig { 69 | // read the compressed lac if available 70 | if gzEnc, ok := annotations[gzipLastAppliedConfigAnnotation]; ok { 71 | gzDec, err := base64.StdEncoding.DecodeString(gzEnc) 72 | if err != nil { 73 | log.Fatal(err) 74 | } 75 | 76 | var buf bytes.Buffer 77 | buf.Write(gzDec) 78 | 79 | zr, err1 := gzip.NewReader(&buf) 80 | 81 | lacBuf := new(strings.Builder) 82 | _, err2 := io.Copy(lacBuf, zr) 83 | 84 | err3 := zr.Close() 85 | 86 | // in case of any error, fall back to the uncompressed lac 87 | if err1 == nil && err2 == nil && err3 == nil { 88 | lac = lacBuf.String() 89 | } 90 | } 91 | } 92 | 93 | return strings.TrimRight(lac, "\r\n") 94 | } 95 | 96 | func getPatch(gvk k8sschema.GroupVersionKind, original []byte, modified []byte, current []byte) (pt k8stypes.PatchType, p []byte, err error) { 97 | versionedObject, err := scheme.Scheme.New(gvk) 98 | switch { 99 | case k8sruntime.IsNotRegisteredError(err): 100 | pt = k8stypes.MergePatchType 101 | 102 | preconditions := []mergepatch.PreconditionFunc{ 103 | mergepatch.RequireKeyUnchanged("kind"), 104 | mergepatch.RequireMetadataKeyUnchanged("name"), 105 | } 106 | 107 | p, err = jsonmergepatch.CreateThreeWayJSONMergePatch(original, modified, current, preconditions...) 108 | if err != nil { 109 | return pt, p, fmt.Errorf("getPatch failed: %s", err) 110 | } 111 | case err != nil: 112 | return pt, p, fmt.Errorf("getPatch failed: %s", err) 113 | case err == nil: 114 | pt = k8stypes.StrategicMergePatchType 115 | 116 | lookupPatchMeta, err := strategicpatch.NewPatchMetaFromStruct(versionedObject) 117 | if err != nil { 118 | return pt, p, fmt.Errorf("getPatch failed: %s", err) 119 | } 120 | 121 | p, err = strategicpatch.CreateThreeWayMergePatch(original, modified, current, lookupPatchMeta, true) 122 | if err != nil { 123 | return pt, p, fmt.Errorf("getPatch failed: %s", err) 124 | } 125 | } 126 | 127 | return pt, p, nil 128 | } 129 | 130 | // log error including caller name 131 | func logError(m error) error { 132 | pc, _, _, _ := runtime.Caller(1) 133 | fn := runtime.FuncForPC(pc) 134 | 135 | return fmt.Errorf("%s: %s", fn.Name(), m) 136 | } 137 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "flag" 6 | "log" 7 | 8 | "github.com/hashicorp/terraform-plugin-sdk/v2/plugin" 9 | "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" 10 | "github.com/kbst/terraform-provider-kustomize/kustomize" 11 | ) 12 | 13 | func main() { 14 | var debugMode bool 15 | 16 | flag.BoolVar(&debugMode, "debug", false, "set to true to run the provider with support for debuggers like delve") 17 | flag.Parse() 18 | 19 | opts := &plugin.ServeOpts{ 20 | ProviderFunc: func() *schema.Provider { 21 | return kustomize.Provider() 22 | }, 23 | } 24 | 25 | if debugMode { 26 | err := plugin.Debug(context.Background(), "registry.terraform.io/kbst/kustomization", opts) 27 | if err != nil { 28 | log.Fatal(err.Error()) 29 | } 30 | return 31 | } 32 | 33 | plugin.Serve(opts) 34 | } 35 | -------------------------------------------------------------------------------- /test-schema-migration._tf: -------------------------------------------------------------------------------- 1 | terraform { 2 | required_providers { 3 | kustomization = { 4 | source = "kbst/kustomization" 5 | # all test versions are placed as 1.0.0 6 | # in .terraform/plugins for tests 7 | version = "<0.8.0" 8 | } 9 | } 10 | required_version = ">= 0.13" 11 | } 12 | 13 | data "kustomization_build" "test" { 14 | path = "kustomize/test_kustomizations/basic/initial" 15 | } 16 | 17 | resource "kustomization_resource" "from_build" { 18 | for_each = data.kustomization_build.test.ids 19 | 20 | manifest = data.kustomization_build.test.manifests[each.value] 21 | } 22 | 23 | data "kustomization_overlay" "test" { 24 | namespace = "test-overlay" 25 | 26 | resources = [ 27 | "kustomize/test_kustomizations/basic/initial" 28 | ] 29 | 30 | patches { 31 | patch = <<-EOF 32 | - op: add 33 | path: /spec/template/spec/containers/0/env 34 | value: [{"name": "TEST", "value": "true"}] 35 | EOF 36 | 37 | target = { 38 | group = "apps" 39 | version = "v1" 40 | kind = "Deployment" 41 | name = "test" 42 | } 43 | } 44 | } 45 | 46 | resource "kustomization_resource" "from_overlay" { 47 | for_each = data.kustomization_overlay.test.ids 48 | 49 | manifest = data.kustomization_overlay.test.manifests[each.value] 50 | } 51 | -------------------------------------------------------------------------------- /test.tf: -------------------------------------------------------------------------------- 1 | terraform { 2 | required_providers { 3 | kustomization = { 4 | source = "kbst/kustomization" 5 | # all test versions are placed as 1.0.0 6 | # in .terraform/plugins for tests 7 | version = ">= 1.0.0" 8 | } 9 | } 10 | required_version = ">= 0.13" 11 | } 12 | 13 | data "kustomization_build" "test" { 14 | path = "kustomize/test_kustomizations/basic/initial" 15 | } 16 | 17 | resource "kustomization_resource" "from_build" { 18 | for_each = data.kustomization_build.test.ids 19 | 20 | manifest = data.kustomization_build.test.manifests[each.value] 21 | } 22 | 23 | data "kustomization_overlay" "test" { 24 | namespace = "test-overlay" 25 | 26 | resources = [ 27 | "kustomize/test_kustomizations/basic/initial" 28 | ] 29 | 30 | patches { 31 | patch = <<-EOF 32 | - op: add 33 | path: /spec/template/spec/containers/0/env 34 | value: [{"name": "TEST", "value": "true"}] 35 | EOF 36 | 37 | target { 38 | group = "apps" 39 | version = "v1" 40 | kind = "Deployment" 41 | name = "test" 42 | } 43 | } 44 | } 45 | 46 | resource "kustomization_resource" "from_overlay" { 47 | for_each = data.kustomization_overlay.test.ids 48 | 49 | manifest = data.kustomization_overlay.test.manifests[each.value] 50 | } 51 | -------------------------------------------------------------------------------- /tests/fakekubeconfig: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | clusters: 3 | - cluster: 4 | certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUM1ekNDQWMrZ0F3SUJBZ0lCQURBTkJna3Foa2lHOXcwQkFRc0ZBREFWTVJNd0VRWURWUVFERXdwcmRXSmwKY201bGRHVnpNQjRYRFRJeE1EUXhNVEV5TWpZek5sb1hEVE14TURRd09URXlNall6Tmxvd0ZURVRNQkVHQTFVRQpBeE1LYTNWaVpYSnVaWFJsY3pDQ0FTSXdEUVlKS29aSWh2Y05BUUVCQlFBRGdnRVBBRENDQVFvQ2dnRUJBTjJLCjBYVE1pU2pPSGtyeEJoYTJ4SUdrUFZGKzRFaWgvazhJT0l4SW1EUVBPT2U4Q0V0UEFsaXhzM2l5ajF2RUFFajEKUEQva0lENW9GWmJYOHExWWJQVmcrckJ1dTZpdVYrK0JacUZDNEJuU1NQTmE0MEdtamt0L3JwR3phMUF2U2RzYgplMDVlUFQzV3d5dVZVVWNYeDVsYS9LSllqMHk2N2VKalYvVll5THk0WGFidWNXTVFuR1hsU2xGZkJZMmMrWURICmppY0ZIVkVWWWMzQkloZ1IxRU51My93TkdkTlpodVRDRUtjUzRUdVFYb3ZkWEJLdDdzYW94N3RoWkRLZTZQUWMKQk8rRXVoYVRlelhFWHAwT25ZL3U4QlBscUl1bWFJV2ZUemVlQ0g4YXpZaDFpcTRNZGhWWUw4bjRsM2h0NUlYZgpQa294OHRYZUhKN0t0RDJJZ2xjQ0F3RUFBYU5DTUVBd0RnWURWUjBQQVFIL0JBUURBZ0trTUE4R0ExVWRFd0VCCi93UUZNQU1CQWY4d0hRWURWUjBPQkJZRUZGc1ZtaXd1bldXSXZiV0M0YkxMQ3VwZytPRUlNQTBHQ1NxR1NJYjMKRFFFQkN3VUFBNElCQVFDODRmK1R3QmpyaExvb2x1amJPVWlZQjJOc05hK2RHWUhNMG1WaHNHVUl4Q25KMUlVYQpabDdqRFh2bWtMNGsyekhhTm5XK0ZDY2J1S21xM3FIa1Y4NE9xRHlkcXB0MGtwdWRQbzZoZlJxR0xEM2NLSkF4CnhlQk9JM2hMOWIvUkF6dVFuOCtNeHNJNGVMaXFCcCtJeXZ4WkhSZklHSzBuZkw0MzJDVDlQRGw0bVEveFZNWTQKUEp6NmRteGorN2hkVmpEY3dMRGFVYmdNN25GUklDTkk5cEJIMmlrUEVqRFVseUFnL201UFRMdklKUXJyMTVlVQpMMGE5ajllcW1lL2tzYlBkaDVuc1V1MkZQMm1OazdKaHprNlgwZFdlZTA4S0l2L3hoeWhUZHNwaGE1cFcwTmFxCjBMREZrcWxsL0dPMlBuMkNuWGM1Y3lkeUppRGMrU1hUYnpROAotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg== 5 | server: https://127.0.0.1:43779 6 | name: kind-kind 7 | contexts: 8 | - context: 9 | cluster: kind-kind 10 | user: kind-kind 11 | name: kind-kind 12 | current-context: kind-kind 13 | kind: Config 14 | preferences: {} 15 | users: 16 | - name: kind-kind 17 | user: 18 | client-certificate-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURFekNDQWZ1Z0F3SUJBZ0lJTmhaYWNpRXhzcTB3RFFZSktvWklodmNOQVFFTEJRQXdGVEVUTUJFR0ExVUUKQXhNS2EzVmlaWEp1WlhSbGN6QWVGdzB5TVRBME1URXhNakkyTXpaYUZ3MHlNakEwTVRFeE1qSTJOREJhTURReApGekFWQmdOVkJBb1REbk41YzNSbGJUcHRZWE4wWlhKek1Sa3dGd1lEVlFRREV4QnJkV0psY201bGRHVnpMV0ZrCmJXbHVNSUlCSWpBTkJna3Foa2lHOXcwQkFRRUZBQU9DQVE4QU1JSUJDZ0tDQVFFQXpCempYWmtNRGR2MlF2blIKYTdIcitrby9hc2trWnY0VmhvcGl2OHJNb2FXbFhNSGtUUDgzZ0x3ZEp2bGlVbUVQS0tObURFbmJJQ1E4OXNDdgorcW1HcnY2Z284eG42WVVJaHlEZHpMSExPNllWL3JiV2d4QjhRMXQ4T2VEbTAyamlCcnpadUhOT3RIZFRlZE1qCmtDNXI0d0U5OUxTNEtzZ3dKOGpnU21tOWxEZktYeGJ3YWRybythWUMrUFIxWEhQY0cvb1dFcVhOZHpFd1V5c2kKZkNvdllIQ0l2cHhpTW4va2ZUSWNGb0c2OEZES1Y0M0w2d2NIcmRUM0JvNDd6T2daVjRXR1dhWFFiV2dYL1V0cwpFdU5sSWdFZXI4WWFDWDhnY0x1TkI2OUdXWFNCeENLd09VREgyTm40eW5adksrNjdlVFdibU9GaEl5MnJFc29tCjBqaEhZd0lEQVFBQm8wZ3dSakFPQmdOVkhROEJBZjhFQkFNQ0JhQXdFd1lEVlIwbEJBd3dDZ1lJS3dZQkJRVUgKQXdJd0h3WURWUjBqQkJnd0ZvQVVXeFdhTEM2ZFpZaTl0WUxoc3NzSzZtRDQ0UWd3RFFZSktvWklodmNOQVFFTApCUUFEZ2dFQkFEYWRLNm9YMVNVOGRYRVVJVmRlZlU3WS9TY2tkN0dEU3BjZFRLZDNSNEFpM3FNb1grMU9FLy9wCndONzlWWDV3eVhMQWRrV3QrdWlNRGpaOEdQMlBPczFyRERleStmdStCZzF6OE1Nd1ZUa2RTc0Z2Z1hHQXZ1VzgKWFNraE00OW8wVVAzdmZza1F1MU9Da1dKaXJlSVNjSEF5dEMvQ1ROMTU4Y3kwKzdtV3F3MjgvMldCdm5LZlFqWApWbnVOb0hpNzUzV2F5dGczWmxuN3BJWVhuQzltc2JKaGFKNGxDRzMxSEpXbkY2WmR4R05tcHI3a1duVEQxS01TCjVNWllhd3B6eEw0WU95WG9zNGEyMjVrdy9paHROQmJwU3BoWFNicDB6czMrdHpnQkRMNkZUazFxSnI1NE9YWWoKUTNwbG5QTnkrby9mTkw1bmYvZ3dqSkJ1d293czB1OD0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo= 19 | client-key-data: LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFb3dJQkFBS0NBUUVBekJ6alhaa01EZHYyUXZuUmE3SHIra28vYXNra1p2NFZob3BpdjhyTW9hV2xYTUhrClRQODNnTHdkSnZsaVVtRVBLS05tREVuYklDUTg5c0N2K3FtR3J2NmdvOHhuNllVSWh5RGR6TEhMTzZZVi9yYlcKZ3hCOFExdDhPZURtMDJqaUJyelp1SE5PdEhkVGVkTWprQzVyNHdFOTlMUzRLc2d3SjhqZ1NtbTlsRGZLWHhidwphZHJvK2FZQytQUjFYSFBjRy9vV0VxWE5kekV3VXlzaWZDb3ZZSENJdnB4aU1uL2tmVEljRm9HNjhGREtWNDNMCjZ3Y0hyZFQzQm80N3pPZ1pWNFdHV2FYUWJXZ1gvVXRzRXVObElnRWVyOFlhQ1g4Z2NMdU5CNjlHV1hTQnhDS3cKT1VESDJObjR5blp2Sys2N2VUV2JtT0ZoSXkyckVzb20wamhIWXdJREFRQUJBb0lCQUNQV2txbFZmUU5WOHNoUgp1czZRLytFRGRsMFdraGl2VmpJNFRCeG16RVU1bzI1RThRUC83OHZmdTdLaktQdFQ1V2g2UUNtNk1ncFRzb3lVCnlwRlZnTHRySStOK3VXUU1Jckl2T0NKL3VUSnc5LzJ3TnJ2dWdoTUZsaXRIYk9BRDAyUGhkc3puR2hPZnUvMXcKOEJhWndBR3NyeWN2TUFMN0FWR0srSzY0SUR4TXV1S09ZenNVdzdha0Mzc3pjUGV6NUNOTEtUcG5TT08wUUFRRQpBdWpoZUQ3engwcWZNSU9lcmlUQ0tUSWRTa09jdmw5bmZjbHowNyttZEZ0b0xFblhtZ0U5bGhQa2hPWHB6VTgvClFQSUhsTjRuUU5RcndEZzdnTXlnaFF3bUovZVptTklXUFFGdDU2RCtUWnQwTUtvSnF2ZitTUVVPNnhlakg2TjAKSlhGQndDa0NnWUVBK0pnNERFZkJLbE9vUkU4MU9SV3BSaUl4Z3lzYUFkTlpWTU00cGNuQnVsK2FkWkNIZVRubQpsd1Frd0VOY3p2MDVOcXlVTG54ei9QUk8wQkFVVTZUMXVnODlJUWwyTTJ6d1pVUlFjRGpyZkVOMEtwemZFeVpFCkZUWnoyNnFIWGNKS1JOZGdVMDh1S2tTTzhlS096Z05mVFZwb2RnWXNjV1BIalBaUzZaTW5yOVVDZ1lFQTBqRnoKbU5aN1pJOVpTakZlVW9WSmlGc3lxT1QvbThsSVI1YmpSWWFqbkNCK1h0dEVOSEF5TnJudzNHTE9nUy9UdnJ4RApwbHEzVXFQQytlcEFLTm5XdnBJNFFtV0NCYVRGVUdrWmw0SjY3U3RCdHA0R096RURjblBOOW5ML2pLQWVQTUQvClZ6K3BBWlZSWmdwMW0vM3pBbEU2KzBYMGN3UkxSLzExTWQ1MmJsY0NnWUVBNGZBWElMSW1rZjJ1dFViNExJWFAKYjNxc1hYYlRFRTJ5cHlNM1hSYmVDREhVQkgzell1Nkk4VUJHMXFkaXRvM1hiaVcwRi92c3Z6NmNVdVlLVTJ0ZQpHbGkzU2t0N0xvb1lnekZ2bWs5aFYzTkhKV09tSzVWZjA1ZkYvU1FrRzhiMkVWTmVyTmtPTUVSWFZ1aCt1aWErCmUyTnNCYmplczcvb0llbk91Wk9SUW5FQ2dZQmU0VUdyK1ExRURFMGk1M3dMUmUwMlp1eE1QdXArMlBJT2xyYksKZUljNy81THJvSkIrRnpNamJ2V2hsZHhmaGtaUHI4M2R0czlQdDJwWXczdm90TVJ4eTdFbmo0aU1vWjhMdUJWOApSY0xWY2hROHFjSm9UNnlkcWxhTGE4ZWRJOTNpVU1BeUV5Tm4rbzMrd0xQc0VVcnpmZFZnL1dmbHowZG9IS29kCk02MUVDd0tCZ0MwQUp5Q1RYemZ5cVJKTEhzeTljMitCc0tGOGdsQkZjdC8vTm15cmpSMUd1bkRpQmFoVmo4V2kKRHJzRnJQcmhRcU9jOHVJb3ZrUW8vWk1UWjdPdDV3bXJMVWpEa2pLaFRuUFpCNEU2d24zNXl0TDB0elhSV2hqNwpLbHlOMlFqaVltRU1WTzBNNzJLdDdIWG1uTmYzRHBKTEVWdWlLSkIrbkE1RGNRaWZMNDhsCi0tLS0tRU5EIFJTQSBQUklWQVRFIEtFWS0tLS0tCg== 20 | -------------------------------------------------------------------------------- /tests/in-cluster.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ServiceAccount 3 | metadata: 4 | name: terraform 5 | namespace: default 6 | --- 7 | apiVersion: rbac.authorization.k8s.io/v1 8 | kind: ClusterRoleBinding 9 | metadata: 10 | name: terraform-admin 11 | roleRef: 12 | apiGroup: rbac.authorization.k8s.io 13 | kind: ClusterRole 14 | name: cluster-admin 15 | subjects: 16 | - apiGroup: "" 17 | kind: ServiceAccount 18 | name: terraform 19 | namespace: default 20 | --- 21 | apiVersion: v1 22 | kind: Pod 23 | metadata: 24 | labels: 25 | run: terraform 26 | name: terraform 27 | namespace: default 28 | spec: 29 | containers: 30 | - command: 31 | - sleep 32 | - "100000" 33 | image: hashicorp/terraform:1.0.5 34 | imagePullPolicy: IfNotPresent 35 | name: terraform 36 | workingDir: /terraform 37 | serviceAccount: terraform 38 | -------------------------------------------------------------------------------- /tests/kubestack-starter-kind/.gitignore: -------------------------------------------------------------------------------- 1 | # Local .terraform directories 2 | **/.terraform/* 3 | 4 | # .tfstate files 5 | *.tfstate 6 | *.tfstate.* 7 | 8 | # .user home directory 9 | .user/ 10 | -------------------------------------------------------------------------------- /tests/kubestack-starter-kind/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM kubestack/framework:v0.18.2-beta.0-kind 2 | -------------------------------------------------------------------------------- /tests/kubestack-starter-kind/README.md: -------------------------------------------------------------------------------- 1 | # Welcome to Kubestack 2 | 3 | This repository uses [Kubestack][1]. Kubestack is the open source GitOps framework for teams that want to automate infrastructure, not reinvent automation. 4 | 5 | - Cluster infrastructure and cluster services are defined using Terraform modules. 6 | - Popular cluster services are available from the Terraform module [catalog][2]. 7 | - Both cluster and cluster service modules follow the Kubestack [inheritance model][3] to prevent configuration drift between environments. 8 | - All changes follow the same four-step process. 9 | 10 | Full [framework documentation][4] is available online. 11 | 12 | ## Making changes 13 | 14 | To make changes to the Kubernetes cluster(s), supporting infrastructure or the Kubernetes services defined in this repository follow the Kubestack [GitOps process][5]. The GitOps process ensures that changes are safely applied by first reviewing the proposed changes, then validating the changes against the _ops_ environment and finally promoting the changes to be applied against the _apps_ environment by setting a tag. 15 | 16 | To accelerate the developer workflow an auto-updating [development environment][6] can be run on localhost using the `kbst local apply` command. 17 | 18 | 1. Change 19 | 20 | Make changes to the configuration in a new branch. Commit the changed configuration and push your branch. The pipeline runs `terraform plan` against the _ops_ workspace. 21 | 22 | ```shell 23 | # checkout a new branch from main 24 | git checkout -b examplechange main 25 | 26 | # make your changes 27 | 28 | # commit your changes 29 | git commit # write a meaningful commit message 30 | 31 | # push your changes 32 | git push origin examplechange 33 | ``` 34 | 35 | 1. Review 36 | 37 | Request a peer review of your changes. Team members review the changes and the Terraform plan. If reviewers require changes, make additional commits in the branch. 38 | 39 | ```shell 40 | # make sure you're in the correct branch 41 | git checkout examplechange 42 | 43 | # make changes required by the review 44 | 45 | # commit and push the required changes 46 | git commit # write a meaningful commit message 47 | git push origin examplechange 48 | ``` 49 | 50 | 1. Merge 51 | 52 | If approved, merge your changes to main, to apply them against the _ops_ environment. After applying to _ops_ was successful, the pipeline runs Terraform plan against the _apps_ environment. 53 | 54 | ```shell 55 | # you can merge on the commandline 56 | # or by merging a pull request 57 | git checkout main 58 | git merge examplechange 59 | git push origin main 60 | ``` 61 | 62 | 1. Promote 63 | 64 | Review the previous _apps_ environment plan and tag the merge commit to promote the same changes to the _apps_ environment. 65 | 66 | ```shell 67 | # make sure you're on the correct commit 68 | git checkout main 69 | git pull 70 | git log -1 71 | 72 | # if correct, tag the current commit 73 | # any tag prefixed with `apps-deploy-` 74 | # will trigger the pipeline 75 | git tag apps-deploy-$(date -I)-0 76 | 77 | # in case of multiple deploys on the same day, 78 | # increase the counter 79 | # e.g. git tag apps-deploy-2020-05-14-1 80 | ``` 81 | 82 | ## Manual operations 83 | 84 | In case of the automation being unavailable, upgrades requiring manual steps or in disaster recovery scenarios run Terraform and the cloud CLI locally. Kubestack provides container images bundling all dependencies to use for both automated and manual operations. 85 | 86 | 1. Exec into container 87 | 88 | ```shell 89 | # Build the container image 90 | docker build -t kubestack . 91 | 92 | # Exec into the container image 93 | # add docker socket mount for local dev 94 | # -v /var/run/docker.sock:/var/run/docker.sock 95 | docker run --rm -ti \ 96 | -v `pwd`:/infra \ 97 | kubestack 98 | ``` 99 | 100 | 1. Authenticate providers 101 | 102 | Credentials are cached inside the `.user` directory. The directory is excluded from Git by the default `.gitignore`. 103 | 104 | ```shell 105 | # for AWS 106 | aws configure 107 | 108 | # for Azure 109 | az login 110 | 111 | # for GCP 112 | gcloud init 113 | gcloud auth application-default login 114 | ``` 115 | 116 | 1. Select desired environment 117 | 118 | ```shell 119 | # for ops 120 | terraform workspace select ops 121 | 122 | # or for apps 123 | terraform workspace select apps 124 | ``` 125 | 126 | 1. Run Terraform commands 127 | 128 | ```shell 129 | # run terraform init 130 | terraform init 131 | 132 | # run, e.g. terraform plan 133 | terraform plan 134 | ``` 135 | 136 | [1]: https://www.kubestack.com 137 | [2]: https://www.kubestack.com/catalog 138 | [3]: https://www.kubestack.com/framework/documentation/inheritance-model 139 | [4]: https://www.kubestack.com/framework/documentation 140 | [5]: https://www.kubestack.com/framework/documentation/gitops-process 141 | [6]: https://www.kubestack.com/framework/documentation/tutorial-develop-locally#provision-local-clusters 142 | -------------------------------------------------------------------------------- /tests/kubestack-starter-kind/kind_zero_cluster.tf: -------------------------------------------------------------------------------- 1 | module "kind_zero" { 2 | source = "github.com/kbst/terraform-kubestack//kind/cluster?ref=v0.18.2-beta.0" 3 | 4 | configuration = { 5 | # Settings for Apps-cluster 6 | apps = { 7 | name_prefix = "kind" 8 | base_domain = "infra.127.0.0.1.xip.io" 9 | 10 | # clusters always have at least one control-plane node 11 | # uncommenting extra_nodes below will give you a cluster 12 | # with 3 control-plane nodes and 3 worker nodes 13 | # extra_nodes = "control-plane,control-plane,worker,worker,worker" 14 | } 15 | 16 | # Settings for Ops-cluster 17 | ops = { 18 | # optionally reduce number of ops nodes 19 | # extra_nodes = "worker" 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /tests/kubestack-starter-kind/kind_zero_providers.tf: -------------------------------------------------------------------------------- 1 | provider "kustomization" { 2 | alias = "kind_zero" 3 | kubeconfig_raw = module.kind_zero.kubeconfig 4 | } 5 | -------------------------------------------------------------------------------- /tests/kubestack-starter-kind/kind_zero_test_module.tf: -------------------------------------------------------------------------------- 1 | module "kind_zero_test_module" { 2 | providers = { 3 | kustomization = kustomization.kind_zero 4 | } 5 | 6 | source = "github.com/kbst/catalog//src/test?ref=test-v0.0.2-kbst.0" 7 | 8 | configuration = { 9 | apps = { 10 | variant = "overlay" 11 | 12 | name_prefix = "prefix-" 13 | name_suffix = "-suffix" 14 | 15 | namespace = "test-module" 16 | 17 | additional_resources = [ 18 | "${path.root}/manifests/extra_configmap.yaml" 19 | ] 20 | 21 | common_annotations = { 22 | "test-annotation" = "test" 23 | } 24 | 25 | common_labels = { 26 | "test-label" = "test" 27 | } 28 | 29 | labels = [{ 30 | pairs = { 31 | "test-label-only" = "test" 32 | } 33 | }] 34 | 35 | generator_options = { 36 | annotations = { 37 | annotation-generated = "test" 38 | } 39 | 40 | labels = { 41 | label-generated = "test" 42 | } 43 | 44 | disable_name_suffix_hash = false 45 | } 46 | 47 | config_map_generator = [{ 48 | name = "test-generated" 49 | namespace = "test-module" 50 | behavior = "create" 51 | literals = [ 52 | "KEY=VALUE" 53 | ] 54 | }] 55 | 56 | secret_generator = [{ 57 | name = "secret-readme" 58 | namespace = "test-module" 59 | behavior = "create" 60 | type = "generic" 61 | files = [ 62 | "${path.root}/README.md" 63 | ] 64 | }] 65 | 66 | images = [{ 67 | name = "busybox" 68 | new_name = "busybox" 69 | new_tag = "latest" 70 | }] 71 | 72 | patches = [{ 73 | patch = <<-EOF 74 | apiVersion: apps/v1 75 | kind: Deployment 76 | metadata: 77 | name: test 78 | spec: 79 | template: 80 | spec: 81 | containers: 82 | - name: busybox 83 | command: 84 | - sleep 85 | - "30" 86 | EOF 87 | 88 | target = { 89 | group = "apps" 90 | version = "v1" 91 | kind = "Deployment" 92 | name = "test" 93 | } 94 | }] 95 | 96 | replicas = [{ 97 | name = "test" 98 | count = 2 99 | }] 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /tests/kubestack-starter-kind/manifests/.gitempty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kbst/terraform-provider-kustomization/adf37d2cbfc6f5fc6f3bff008397b98939ab3915/tests/kubestack-starter-kind/manifests/.gitempty -------------------------------------------------------------------------------- /tests/kubestack-starter-kind/manifests/extra_configmap.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ConfigMap 3 | metadata: 4 | name: test-extra 5 | -------------------------------------------------------------------------------- /tests/kubestack-starter-kind/versions.tf: -------------------------------------------------------------------------------- 1 | terraform { 2 | required_providers { 3 | kustomization = { 4 | source = "kbst/kustomization" 5 | } 6 | } 7 | 8 | required_version = ">= 0.15" 9 | } 10 | --------------------------------------------------------------------------------