Use computed value as default in variable

55 views
Skip to first unread message

Gonzalo Hernández Casaseca

unread,
May 1, 2019, 12:44:13 PM5/1/19
to Terraform

I have a module with several variables, I was wondering if it is possible to let terraform assign a computed value as default of a variable.


Example:

I had this module to create a GKE cluster, I might want to specify the engine version, but if I don't want to, I want terraform to use the computed value. So something like this:


Module declaration:

variable "gke_version" {
  description
= "GKE version"
 
default = <computed>
}


resource "google_container_cluster" "gke_cluster" {
  provider
= "google-beta"
  name
= "${var.name}"
  network
= "${var.network}"
  google_container_engine_versions
= "gke_version"
}


Module usage using a custom value:

module "test1_gke_cluster" {
  source
= "gke_cluster"
  cluster_name
= "test"
  network
= "default"
  gke_version
="11.6"
}


Module usage without using any value:

module "test2_gke_cluster" {
  source
= "gke_cluster"
  cluster_name
= "test"
  network
= "default"
}

Jd Daniel

unread,
May 2, 2019, 6:35:11 PM5/2/19
to Terraform
You just add it as an optional variable, aka

  ○ → cat main.tf
  ## tf init ; tf plan -var hello=foo -var world=bar

  variable "gke_version" {
    default = ""
  }

  resource "template_file" "example" {
    template = "${var.gke_version}"
  }

  output "rendered" {
    value = "${template_file.example.rendered}"
  }

And when its not required, don't pass it as a param...

  ○ → tf plan
  .......
  Terraform will perform the following actions:

   + template_file.example
       id:       <computed>
       rendered: <computed>

Or pass it in when required

  ○ → tf plan -var 'gke_version=12'
  ..........
  Terraform will perform the following actions:

   + template_file.example
       id:       <computed>
       rendered: <computed>
       template: "12"

This should work the exact same for modules, by either adding or subtracting it from your statement.
Reply all
Reply to author
Forward
0 new messages