1
votes

when working with the resources of the random provider, it's useful to configure keepers so that the rendered result changes when the related keepers changes. I'd love to define all of my input variables as keepers so that the random_string changes whenever the inputs change.

The minimal example is sth like:

variable "var1"         { type = "string" }
variable "var2"         { type = "string" }

resource "random_string" "rnd" {
  length = 16
  special = false
  keepers = {
      variables = "${sha256(jsonencode(var))}"
  }
}

output "rnd" {
  value = "${random_string.rnd.result}"
}

Unfortunately this will create this error:

random_string.rnd: invalid variable syntax: "var". Did you mean 'var.var'? If this is part of inline `template` parameter

then you must escape the interpolation with two dollar signs. For example: ${a} becomes $${a}.

The only solution I found so far is to "embed" all of the input variables into the resource definition like so:

variable "var1"         { type = "string" }
variable "var2"         { type = "string" }

resource "random_string" "rnd" {
  length = 16
  special = false
  keepers = {
      variables = "${sha256("${var.var1}${var.var2}")}"
  }
}

Is there a more flexible way to solve this in terraform? Thx

1

1 Answers

1
votes

I also had this issue already in another use case. But there is no proper solution so far as you can not access all available variables. The only solution is the one you described in your question already.

In addition you could use e.g a template_file or a locale to move the ugly part into another resource:

locals {
  var-map = {
    var1 = "${var.var1}"
    var2 = "${var.var2}"
  }
}

resource "random_id" "rnd" {
  byte_length = 8

  keepers = "${local.var-map}"
}