Prevent usage of default kubeconfig by Terraform module

11/14/2019

I'm trying to create some reusable Terraform modules that provision Kubernetes resources on a cluster. My modules do not explicitly configure a Kubernetes provider, expecting that a configured one will be created by the "root" module. I believe this is in line with Terraform best practices.

If the root module "forgets" to provide a configured Kubernetes provider, though, it appears that Terraform will provide one by default, and with the default behaviour of using whatever context may currently be configured in the executing user's kubeconfig. If the user is not paying attention, they may inadvertently end up modifying resources on the wrong cluster.

Is there a way to prevent this behaviour and effectively say "you must explicitly pass in a provider for this module to use"?

-- AwesomeTown
kubernetes
terraform
terraform-provider-kubernetes

1 Answer

11/14/2019

The best option I've come up with is to create a Kubernetes provider in the module like:

# Prevents this module from loading a default context from local kubeconfig when calling module forgets to define a Kubernetes provider
provider "kubernetes" {
  load_config_file = false
}

Then, as long as the calling module provides a different instance, eg:

provider "kubernetes" {
  # properly configure stuff here
}

module "my-module" {
  source              = "blah"
  providers = {
    kubernetes = kubernetes
  }
  etc.
}

you can avoid accidentally using the default provider.

This is fine, but a little non-obvious until you're used to the pattern.

-- AwesomeTown
Source: StackOverflow