Élodie Petit
Élodie Petit

Reputation: 5914

Reusing Terraform modules without exposing any variables

Consider the following folder structure:

.
├── network-module/
│   ├── main.tf
│   └── variables.tf
├── dev.tfvars
├── prod.tfvars
├── main.tf
└── variables.tf

This is a simple Terraform configuration running under a GitLab pipeline.

network-module contains some variables for the network settings that change depending on the environment (dev, prod, etc) we deploy.

The main module has an environment variable that can be used to set the target environment.

What I want to achieve is to hide the variables that the network module needs from the parent module, so that users only need to specify the environment name and can omit the network configuration for the target environment altogether.

Using -var-file when running plan or apply works, but to do that I need to include all the variables the submodule needs in the parent module's variable file.

Basically, I don't want all the variables exposed to the outside world.

One option that comes to mind is to run some scripts inside the pipeline and change the contents of the configuration through string manipulation, but that feels wrong.

Do I have any other options?

Upvotes: 0

Views: 330

Answers (1)

theherk
theherk

Reputation: 7546

Sure, just set your per-environment configuration in the root module.

locals {
  network_module_args = {
    dev = {
      some_arg = "arg in dev"
    }
    prod = {
      some_arg = "arg in prod"
    }
  }
}

module "network_module" {
  source = "network-module"

  some_arg = lookup(local.network_module_args, environment, "")
}

Upvotes: 1

Related Questions