Terraform - How to pass environment variables to sub modules in terraform

Viewed 6067

My solution:

├── main.tf
├── modules
│   ├── cluster1
│   │   ├── cluster1.tf
│   │   ├── main.tf
│   │   ├── output.tf
│   │   └── variables.tf
│   ├── cluster2
│   │   ├── cluster.tf
│   │   ├── main.tf
│   │   ├── output.tf
│   │   └── variables.tf
│   └── trafficmanager
│       ├── main.tf
│       ├── output.tf
│       ├── trafficmanager.tf
│       └── variables.tf
├── README.md
└── variables.tf

in order for me to create a Azure k8s clusters, each cluster requires service principal id and secret. i would be very interested to see some examples on how how to pass environment variables containing service principal and secret to each cluster.

3 Answers

Terraform will read environment variables in the form of TF_VAR_name to find the value for a variable. For example, the TF_VAR_access_key variable can be set to set the access_key variable.

Example

export TF_VAR_region=us-west-1 # normal string
export TF_VAR_alist='[1,2,3]' # array
export TF_VAR_amap='{ foo = "bar", baz = "qux" }' # map

Pass module to terraform module

variable "region" {}
variable "alist" {}
variable "map" {}

module "test" {
  source = "./module/testmodule" # module location
  region = "${var.region}"
  list   = "${var.alist}"
  map    = "${var.map}"
}

More information in this link and some example

you can specify variables in the module and pass information to them:

module.tf:

variable "hack" {}
variable "reference" {
  "type" = "map"
}    
variable "ports" {
  "default" = [2379, 6443]
}

module invocation:

module "master" {
  source = "./vmLoop"

  vmName    = "master"
  reference = "${var.reference}"
  hack      = "${element(azurerm_subnet.subnets.*.id, 1)}"
}

Annoyingly it seems you have to duplicate the definition in the "root" module (i.e. the entry point, if I'm understanding TF terminology correctly). E.g:

# "cluster" module defines variable:
common/terraform/modules/cluster/variables.tf:
variable "environment_root" {
    type = string
}

# "cluster" module uses it:
common/terraform/modules/cluster/nodes.tf:
...
metadata = {
    environment = var.environment_root
  }
...

# "root" module which uses cluster module defines it:
dev/terraform/variables.tf:
variable "environment_root" {
    type = string
}

# "root" module passes it to cluster module:
dev/terraform/main.tf:
module "cluster" {
    environment_root = var.environment_root
...
}

This can then be set e.g. :

export TF_VAR_environment_root=whatever
terraform apply

Love for someone to tell me another way...

Related