How to define optional variables in Terraform with default values defined in Consul
Asked Answered
N

3

15

I have a Terraform script with some variables populated from Consul. I want to use this script in two different scenarios:

  • Scenario 1. Everything goes right using default values from Consul.
  • Scenario 2. I need to override some variables.

I've checked Terraform documentation and noticed that I can't use a variable defined in Consul as a default value for some another variable. So I ended up with following workaround:

## vars.tf
## emulating undefined value using "null" string
variable "my_optional_variable" { default = "null" } 

## main.tf
my_optional_variable = "${var.my_optional_variable == "null" ? data.consul_keys.my_optional_variable : var.my_optional_variable}"

Can somebody show me a better way to do it? How to avoid a hack with a "null" string?

Thanks

Nodular answered 22/5, 2018 at 13:20 Comment(0)
C
21

Another option is coalesce which works with empty strings so is slightly better than your "null" string.

Given your scenario or a similar case with two variables/data sources

variable "my_default_value" {
  default = "CentOS 7"
}
variable "my_optional_variable" {
  default = ""
}

You can take the "first non-empty value from the given arguments. At least two arguments must be provided."

data "openstack_images_image_v2" "bastion_image" {
  name = "${coalesce(var.my_optional_variable, var.my_default_value)}"
}
Cordelier answered 9/8, 2018 at 2:37 Comment(1)
The best answer! Thanks a lot!Doughnut
S
8

if your optional variable needs to come externally or from a declared resource you can use count and ternaries to accomplish this.

variable "my_variable_id" {
    type = string
    default = ""
}

resource "cloud_resource" "my_resource" {
    count = var.my_variable == "" ? 1 : 0
    other_params = {...}
}

resource "dependent_cloud_resource" "my_other_resource" {
    other_resource_id = var.my_variable_id == "" ? cloud_resrouce.my_resource[0].id : var.my_variable_id
}


Solangesolano answered 2/9, 2021 at 15:31 Comment(0)
J
4

You can use an override file. So, if you have vars.tf containing:

variable "my_optional_variable" {
  default = "null"
}

And override.tf that contains:

variable "my_optional_variable" {
  default = "not null"
}

Then ${var.my_optional_variable} should equal not null. Override files are loaded last and merged into your configuration. Rather then appended together like other .tf files in the directory.

Jobie answered 22/5, 2018 at 18:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.