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

12/19/2018

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.

-- user399256
azure
azure-aks
azure-kubernetes
kubernetes
terraform

2 Answers

12/19/2018

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

-- Abu Hanifa
Source: StackOverflow

12/19/2018

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)}"
}
-- 4c74356b41
Source: StackOverflow