{"id":13742670,"url":"https://github.com/hashicorp/terraform-k8s","last_synced_at":"2025-08-11T07:32:24.082Z","repository":{"id":38345209,"uuid":"225920047","full_name":"hashicorp/terraform-k8s","owner":"hashicorp","description":"Terraform Cloud Operator for Kubernetes","archived":false,"fork":false,"pushed_at":"2024-08-22T13:29:19.000Z","size":16155,"stargazers_count":454,"open_issues_count":46,"forks_count":71,"subscribers_count":28,"default_branch":"main","last_synced_at":"2024-10-29T17:13:36.311Z","etag":null,"topics":["kubernetes","operator","terraform","terraform-cloud"],"latest_commit_sha":null,"homepage":"https://learn.hashicorp.com/tutorials/terraform/kubernetes-operator?in=terraform/kubernetes","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mpl-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hashicorp.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":".github/SECURITY.md","support":".github/SUPPORT.md","governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-12-04T17:21:12.000Z","updated_at":"2024-10-14T19:08:27.000Z","dependencies_parsed_at":"2024-06-18T20:11:48.954Z","dependency_job_id":"b1d582a2-56ce-4ab2-accc-6763ad8818c8","html_url":"https://github.com/hashicorp/terraform-k8s","commit_stats":{"total_commits":107,"total_committers":31,"mean_commits":"3.4516129032258065","dds":0.794392523364486,"last_synced_commit":"91cc9327f9e4556dbdda02de3523348e4939fdf1"},"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hashicorp%2Fterraform-k8s","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hashicorp%2Fterraform-k8s/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hashicorp%2Fterraform-k8s/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hashicorp%2Fterraform-k8s/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hashicorp","download_url":"https://codeload.github.com/hashicorp/terraform-k8s/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":229510834,"owners_count":18084444,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["kubernetes","operator","terraform","terraform-cloud"],"created_at":"2024-08-03T05:00:34.839Z","updated_at":"2024-12-13T08:03:06.381Z","avatar_url":"https://github.com/hashicorp.png","language":"Go","funding_links":[],"categories":["Repository is obsolete","Go"],"sub_categories":["Awesome Operators in the Wild"],"readme":"# terraform-k8s - DEPRECATED\n\n⚠️ **This repository is deprecated and no longer actively maintained.** ⚠️\n\nWe strongly encourage users to migrate to the **[HCP Terraform Operator](https://github.com/hashicorp/hcp-terraform-operator)** for a more comprehensive, scalable, and supported solution.\n\n### Why this change?\nThe HCP Terraform Operator provides advanced integration and ongoing support, offering a significantly improved experience for managing your HCP Terraform workflows with Kubernetes.\n\n### Migration Guide\nFor details on migrating your existing setup, please refer to our comprehensive [Migration Guide](https://developer.hashicorp.com/terraform/cloud-docs/integrations/kubernetes/ops-v2-migration).\n\n---\n\n# Terraform Cloud Operator for Kubernetes (v1)\n\nThe Terraform Cloud Operator for Kubernetes provides first-class integration between [Kubernetes](https://kubernetes.io/) and [Terraform Cloud](https://www.hashicorp.com/products/terraform/editions/cloud/) by extending the Kubernetes control plane to enable lifecycle management of cloud and on-prem infrastructure through [Kubernetes manifests](https://kubernetes.io/docs/concepts/cluster-administration/manage-deployment/). Manifests can be deployed and managed using kubectl, [Terraform](https://registry.terraform.io/providers/hashicorp/kubernetes-alpha/latest), Gitops tools, or any other tool that allows you to manage Kubernetes [custom resources](https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/). \n\nThis operator provides a unified way to manage a Kubernetes application and its infrastructure dependencies through a single Kubernetes [CustomResourceDefinition](https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/) (CRD). After the infrastructure dependencies are created, pertinent information such as endpoints and credentials are returned from Terraform Cloud to Kubernetes.\n\n## Use Case\n  * **Manage the lifecycle of cloud and on-prem infrastructure through a single Kubernetes custom resource**  \n    * Install the operator from the corresponding [Helm Chart](https://github.com/hashicorp/terraform-helm) to enable the management of infrastructure services from any Kubernetes cluster.\n    * Provision and manage infrastructure from any provider, such as [AWS](https://registry.terraform.io/providers/hashicorp/aws/latest/docs), [Azure](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs), [GCP](https://registry.terraform.io/providers/hashicorp/google/latest/docs), and any of the hundreds of other [Terraform providers](https://registry.terraform.io/browse/providers), to use them with your existing application configurations, through Terraform Cloud or Terraform Enterprise.\n    * Deploy and Manage your Kubernetes and infrastructure resources in a single git repository, separate git repositories, or directly from a [module](https://www.terraform.io/docs/modules/index.html) in the [Terraform Registry](https://registry.terraform.io/browse/modules), to match your existing operating model.\n    * Provide governance for your infrastructure resources using policy-as-code with [OPA Gatekeeper](https://github.com/open-policy-agent/gatekeeper) and [HashiCorp Sentinel](https://www.hashicorp.com/sentinel/).\n\n\nYou can read more about this project and its potential use cases on our [blog](https://www.hashicorp.com/blog/creating-workspaces-with-the-hashicorp-terraform-operator-for-kubernetes/).\n\nTerraform also enables you to create and publish [custom infrastructure providers](https://learn.hashicorp.com/collections/terraform/providers) through the [Terraform SDK](https://www.terraform.io/docs/extend/plugin-sdk.html). Once you create a new Terraform provider, [publish it to the Terraform Registry](https://www.terraform.io/docs/registry/providers/publishing.html) and then you can consume it with the operator.\n\nJoin us in the [#terraform-providers channel on the Kubernetes Slack](https://kubernetes.slack.com/messages/CJY6ATQH4)  to discuss this, and other Terraform and Kubernetes projects ([Sign up here](http://slack.k8s.io/)). \n\n**Note:**\nThis project is versioned separately from Terraform. Supported Terraform versions must be version 0.12 or above. By versioning this project separately, we can iterate on Kubernetes integrations more quickly and release new versions without forcing Terraform users to do a full Terraform upgrade.\n\nWe take Terraform's security and our users' trust very seriously. If you believe you have found a security issue in the Terraform Cloud Operator for Kubernetes, please responsibly disclose by contacting us at security@hashicorp.com.\n\n## Installation and Configuration\n\n### Namespace\n\nCreate the namespace where you will deploy the operator, Secrets, and Workspace\nresources.\n\n```shell\n$ kubectl create ns $NAMESPACE\n```\n\n### Authentication\n\nThe operator must authenticate to Terraform Cloud. Note that the operator must run within the cluster, which means that it already handles Kubernetes authentication.\n\n1. Generate a Terraform Cloud Team API token at\n   `https://app.terraform.io/app/$ORGANIZATION/settings/teams`, where\n   `$ORGANIZATION` is your organization name.\n\n1. Create a file for storing the API token and open it in a text editor.\n\n1. Insert the generated token (`$TERRAFORM_CLOUD_API_TOKEN`) into the\n   text file formatted for Terraform credentials.\n   ```hcl\n   credentials app.terraform.io {\n     token = \"$TERRAFORM_CLOUD_API_TOKEN\"\n   }\n   ```\n\n1. Create a Kubernetes secret named `terraformrc` in the namespace.\n   Reference the credentials file (`$FILENAME`) created in the previous step.\n   ```shell\n   $ kubectl create -n $NAMESPACE secret generic terraformrc --from-file=credentials=$FILENAME\n   ```\n   Ensure `terraformrc` is the name of the secret, as it is the default secret name defined under the Helm value `syncWorkspace.terraformRC secretName` in the `values.yaml` file.\n\nIf you have the free tier of Terraform Cloud, you will only be able to generate a token for the one team associated with your account. If you have a paid tier of Terraform Cloud, create a separate team for the `operator` with \"Manage Workspaces\" access.\n\nNote that a Terraform Cloud Team API token is a broad-spectrum token. It allows the token holder to create workspaces and execute Terraform runs. You cannot limit the access it provides to a single workspace or role within a team. In order to support a first-class Kubernetes experience, security and access control to this token must be enforced by [Kubernetes Role-Based Access Control (RBAC)](https://kubernetes.io/docs/reference/access-authn-authz/rbac/) policies.\n\n### Workspace Sensitive Variables\n\nSensitive variables in Terraform Cloud workspaces often take the form of credentials for cloud providers or API endpoints. They enable Terraform Cloud to authenticate against a provider and apply changes to infrastructure.\n\nCreate the secret for the namespace that contains all of the sensitive variables required for the workspace.\n\n```shell\n$ kubectl create -n $NAMESPACE secret generic workspacesecrets --from-literal=SECRET_KEY=$SECRET_KEY --from-literal=SECRET_KEY_2=$SECRET_KEY_2 ...\n```\nEnsure `workspacesecrets` is the name of the secret, as it is the default secret name defined under the Helm value `syncWorkspace.sensitiveVariables.secretName` in the `values.yaml` file.\n\nIn order to support a first-class Kubernetes experience, security and access control to these secrets must be enforced by [Kubernetes Role-Based Access Control (RBAC)](https://kubernetes.io/docs/reference/access-authn-authz/rbac/) policies.\n\n### Terraform Version\n\nBy default, the operator will create a Terraform Cloud workspace with\n[a pinned version](https://github.com/hashicorp/terraform-k8s/blob/master/operator/version/version.go) of Terraform.\n\nOverride the Terraform version that will be set for the workspace by changing the Helm value `syncWorkspace.terraformVersion` to the Terraform version of choice.\n\n## Deploy the Operator\n\nUse the [Helm chart](https://github.com/hashicorp/terraform-helm) repository to deploy the Terraform Operator to the namespace you previously created.\n\n```shell\n$ helm repo add hashicorp https://helm.releases.hashicorp.com\n$ helm search repo hashicorp/terraform\n$ helm install --namespace ${NAMESPACE} hashicorp/terraform --generate-name\n```\n\n## Create a Workspace\n\nThe Workspace CustomResource defines a Terraform Cloud workspace, including\nvariables, Terraform module, and outputs.\n\nHere are [examples of Workspace CustomResource](https://github.com/hashicorp/terraform-helm/tree/master/example)..\n\nThe Workspace Spec includes the following parameters:\n\n1. `organization`: The Terraform Cloud organization you would like to use.\n\n1. `secretsMountPath`: The file path defined on the operator deployment that contains the workspace's secrets.\n\nAdditional parameters are outlined below.\n\n### Modules\n\n\u003e The Workspace will only execute Terraform configuration in a module. It will not execute `*.tf` files.\n\nInformation passed to the Workspace CustomResource will be rendered to a template Terraform configuration that uses the `module` block. Specify a module with remote `source`. Publicly available VCS repositories, the Terraform Registry, and private module registry are supported. In addition to `source`, specify a module `version`.\n\n```yaml\nmodule:\n  source: \"hashicorp/hello/random\"\n  version: \"3.1.0\"\n```\n\nThe above Kubernetes definition renders to the following Terraform\nconfiguration.\n\n```hcl\nmodule \"operator\" {\n  source = \"hashicorp/hello/random\"\n  version = \"3.1.0\"\n}\n```\n\n### Variables\n\nVariables for the workspace must equal the module's input variables.\nYou can define Terraform variables in two ways:\n\n1. Inline\n   ```yaml\n   variables:\n     - key: hello\n       value: world\n       sensitive: false\n       environmentVariable: false\n   ```\n\n2. With a Kubernetes ConfigMap reference\n   ```yaml\n   variables:\n     - key: second_hello\n       valueFrom:\n         configMapKeyRef:\n           name: say-hello\n           key: to\n       sensitive: false\n       environmentVariable: false\n   ```\n\nThe above Kubernetes definition renders to the following Terraform\nconfiguration.\n\n```hcl\nvariable \"hello\" {}\n\nvariable \"second_hello\" {}\n\nmodule \"operator\" {\n  source = \"hashicorp/hello/random\"\n  version = \"3.1.0\"\n  hello = var.hello\n  second_hello = var.second_hello\n}\n```\n\nThe operator pushes the values of the variables to the Terraform Cloud\nworkspace. For secrets, set `sensitive` to be `true`. The workspace sets them as write-only. Denote workspace environment variables by setting `environmentVariable` as `true`.\n\nSensitive variables should already be initialized as per [Workspace Sensitive Variables](#workspace-sensitive-variables). You can define them by setting `sensitive: true`. Do not define the value or use a ConfigMap reference, as the read from file will override the value you set.\n\n```yaml\nvariables:\n  - key: AWS_SECRET_ACCESS_KEY\n    sensitive: true\n    environmentVariable: true\n```\n\n### Apply an SSH key to the Workspace (optional)\n\nSSH keys can be used to [clone private modules](https://www.terraform.io/docs/cloud/workspaces/ssh-keys.html). To apply an SSH key to the workspace, specify `sshKeyID` in the Workspace Custom Resource. The SSH key ID can be found in the [Terraform Cloud API](https://www.terraform.io/docs/cloud/api/ssh-keys.html#list-ssh-keys).\n\n```\napiVersion: app.terraform.io/v1alpha1\nkind: Workspace\nmetadata:\n  name: $WORKSPACE\nspec:\n   sshKeyID: $SSHKEYID\n```\n\n### Outputs\n\nIn order to retrieve Terraform outputs, specify the `outputs`\nsection of the Workspace CustomResource. The `key` represents the output key you expect from `terraform output` and `moduleOutputName` denotes the module's output key name.\n\n```yaml\noutputs:\n  - key: my_pet\n    moduleOutputName: pet\n```\n\nThe above Kubernetes definition renders to the following Terraform\nconfiguration.\n\n```hcl\noutput \"my_pet\" {\n  value = module.operator.pet\n}\n```\n\nThe values of the outputs can be consumed from two places:\n\n1. Kubernetes status of the workspace.\n   ```shell\n   $ kubectl describe -n $NAMESPACE workspace $WORKSPACE_NAME\n   ```\n1. ConfigMap labeled `$WORKSPACE_NAME-outputs`. Kubernetes deployments can consume these\n   output values.\n   ```shell\n   $ kubectl describe -n $NAMESPACE configmap $WORKSPACE_NAME-outputs\n   ```\n\n### Deploy\n\nDeploy the workspace after configuring its module, variables, and outputs.\n\n```shell\n$ kubectl apply -n $NAMESPACE -f workspace.yml\n```\n\n### Update a Workspace\n\nThe following changes updates and executes new runs for the Terraform Cloud workspace:\n\n1. `organization`\n1. `module` source or version\n1. `outputs`\n1. Non-sensitive or ConfigMap reference `variables`.\n\nUpdates to sensitive variables *will not* trigger a\nnew execution because sensitive variables are write-only for security\npurposes. The operator is unable to reconcile the upstream value of the\nsecret with the value stored locally. Similarly, ConfigMap references do not trigger updates as the operator does not read the value for comparison.\n\nAfter updating the configuration, re-deploy the workspace.\n\n```shell\n$ kubectl apply -n $NAMESPACE -f workspace.yml\n```\n\n### Delete a Workspace\n\nWhen deleting the Workspace CustomResource, the command line will wait for a few moments.\n\n```shell\n$ kubectl delete -n $NAMESPACE workspace.app.terraform.io/$WORKSPACE_NAME\n```\n\nThis is because the operator is running a [finalizer](https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/#finalizers). The finalizer will execute before the workspace officially deletes in order to:\n\n1. Stop all runs in the workspace, including pending ones\n1. `terraform destroy -auto-approve` on resources in the workspace\n1. Delete the workspace.\n\nOnce the finalizer completes, Kubernetes deletes the Workspace CustomResource.\n\n## Debugging\n\nCheck the status and outputs of the workspace by examining its Kubernetes status. This provides the run ID and workspace ID to debug in the Terraform Cloud UI.\n\n```shell\n$ kubectl describe -n $NAMESPACE workspace $WORKSPACE_NAME\n```\n\nWhen workspace creation, update, or deletion fails, check errors by\nexamining the logs of the operator.\n\n```shell\n$ kubectl logs -n $NAMESPACE $(kubectl get pods -n $NAMESPACE --selector \"component=sync-workspace\" -o jsonpath=\"{.items[0].metadata.name}\")\n```\n\nIf Terraform Cloud returns an error that the Terraform configuration is\nincorrect, examine the Terraform configuration at its ConfigMap.\n\n```shell\n$ kubectl describe -n $NAMESPACE configmap $WORKSPACE_NAME\n```\n\n## Internals\n\n### Why create a namespace and secrets?\n\nThe Helm chart does not include secrets management or injection. Instead, it expects to find secrets mounted as volumes to the operator's deployment. This supports secrets management approaches in Kubernetes that use a volume mount for secrets.\n\nIn order to support a first-class Kubernetes experience, security and access control to these secrets must be enforced by [Kubernetes Role-Based Access Control (RBAC)](https://kubernetes.io/docs/reference/access-authn-authz/rbac/) policies.\n\nFor the Terraform Cloud Team API token, the entire credentials file with the Terraform Cloud API Token is mounted to the filepath specified by `TF_CLI_CONFIG_FILE`. In an equivalent Kubernetes configuration, the following example creates a Kubernetes secret and mount it to the operator at the filepath specified by `TF_CLI_CONFIG_FILE`.\n\n```yaml\n---\n# not secure secrets management\napiVersion: apps/v1\nkind: Secret\nmetadata:\n  name: terraformrc\ntype: Opaque\ndata:\n  credentials: |-\n    credentials app.terraform.io {\n      token = \"$TERRAFORM_CLOUD_API_TOKEN\"\n    }\n---\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: terraform-k8s\nspec:\n  # some sections omitted for clarity\n  template:\n    metadata:\n      labels:\n        name: terraform-k8s\n    spec:\n      serviceAccountName: terraform-k8s\n      containers:\n        - name: terraform-k8s\n          env:\n            - name: TF_CLI_CONFIG_FILE\n              value: \"/etc/terraform/.terraformrc\"\n          volumeMounts:\n          - name: terraformrc\n            mountPath: \"/etc/terraform\"\n            readOnly: true\n      volumes:\n        - name: terraformrc\n          secret:\n            secretName: terraformrc\n            items:\n            - key: credentials\n              path: \".terraformrc\"\n```\n\nSimilar to the Terraform Cloud API Token, the Helm chart mounts\nthem to the operator's deployment for use. It __does not__ mount workspace sensitive variables to the Workspace Custom Resource. This ensures that only the operator has access to read and create sensitive variables as part of the Terraform Cloud workspace.\n\nExamine the deployment in `templates/sync-workspace-deployment.yaml`. The deployment mounts a volume containing the sensitive variables. The file name is the secret's key and file contents is the secret's value. This supports secrets management approaches in Kubernetes that use a volume mount for secrets.\n\n```yaml\n---\n# not secure secrets management\napiVersion: apps/v1\nkind: Secret\nmetadata:\n  name: workspacesecrets\ntype: Opaque\ndata:\n  AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY}\n  GOOGLE_APPLICATION_CREDENTIALS: ${GOOGLE_APPLICATION_CREDENTIALS}\n---\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: terraform-k8s\nspec:\n  # some sections omitted for clarity\n  template:\n    metadata:\n      labels:\n        name: terraform-k8s\n    spec:\n      serviceAccountName: terraform-k8s\n      containers:\n        - name: terraform-k8s\n          volumeMounts:\n          - name: workspacesecrets\n            mountPath: \"/tmp/secrets\"\n            readOnly: true\n      volumes:\n        - name: workspacesecrets\n          secret:\n            secretName: workspacesecrets\n```\n\n### Helm Chart\n\nThe Helm chart consists of several components. The Kubernetes configurations associated with the Helm chart are located under `crds/` and `templates/`.\n\n#### Custom Resource Definition\n\nHelm starts by deploying the Custom Resource Definition for the Workspace. Custom Resource Definitions extend the Kubernetes API. It looks for definitions in the `crds/` of the chart.\n\nThe Custom Resource Definition under `crds/app.terraform.io_workspaces_crd.yaml` defines that the Workspace Custom Resource schema.\n\n#### Role-Based Access Control\n\nIn order to scope the operator to a namespace, Helm assigns a role and service account to the namespace. The role has access to Pods, Secrets, Services, and ConfigMaps. This configuration is located in `templates/`.\n\n#### Namespace Scope\n\nTo ensure the operator does not have access to secrets or resource beyond the namespace, the Helm chart scopes the operator's deployment to a namespace.\n\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: terraform-k8s\nspec:\n  # some sections omitted for clarity\n  template:\n    metadata:\n      labels:\n        name: terraform-k8s\n    spec:\n      serviceAccountName: terraform-k8s\n      containers:\n        - name: terraform-k8s\n          command:\n          - /bin/terraform-k8s\n          - \"--k8s-watch-namespace=$(POD_NAMESPACE)\"\n          env:\n            - name: POD_NAMESPACE\n              valueFrom:\n                fieldRef:\n                  fieldPath: metadata.namespace\n```\n\nWhen deploying, ensure that the namespace is passed into the\n`--k8s-watch-namespace` option. Otherwise, the operator will attempt to access across all namespaces (cluster scope).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhashicorp%2Fterraform-k8s","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhashicorp%2Fterraform-k8s","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhashicorp%2Fterraform-k8s/lists"}