Getting an Environment Variable in Terraform configuration?

Adron picture Adron · Apr 14, 2016 · Viewed 31.6k times · Source

I have two environment variables. One is TF_VAR_UN and another is TF_VAR_PW. Then I have a terraform file that looks like this.

resource "google_container_cluster" "primary" {
    name = "marcellus-wallace"
    zone = "us-central1-a"
    initial_node_count = 3

    master_auth {
        username = ${env.TF_VAR_UN}
        password = ${env.TF_VAR_PW}
    }

    node_config {
        oauth_scopes = [
            "https://www.googleapis.com/auth/compute",
            "https://www.googleapis.com/auth/devstorage.read_only",
            "https://www.googleapis.com/auth/logging.write",
            "https://www.googleapis.com/auth/monitoring"
        ]
    }
}

The two values I'd like to replace with the environment variables TF_VAR_UN and TF_VAR_PW are the values username and password. I tried what is shown above, with no success, and I've toyed around with a few other things but always get syntax issues.

Answer

Liam picture Liam · Apr 17, 2016

I would try something more like this, which seems closer to the documentation.

variable "UN" {}
variable "PW" {}

resource "google_container_cluster" "primary" {
name = "marcellus-wallace"
zone = "us-central1-a"
initial_node_count = 3

master_auth {
    username = "${var.UN}"
    password = "${var.PW}"
}

node_config {
    oauth_scopes = [
        "https://www.googleapis.com/auth/compute",
        "https://www.googleapis.com/auth/devstorage.read_only",
        "https://www.googleapis.com/auth/logging.write",
        "https://www.googleapis.com/auth/monitoring"
    ]
}

With the CLI command being the below.

TF_VAR_UN=foo TF_VAR_PW=bar terraform apply