1

I would like to know if it is possible to use temporary variables inside a for loop for intermediate computation. If yes, what is the syntax to use that, the example is simplified just to illustrate the problem. This example code works. I've commented the portion which doesn't work, but would like to know how to use intermediate variable. Thanks!


locals {
  nestedmap = <<-EOT
  user-john:
    db:  "db34"
    tables:
      t1:
        rows: 4
      t2:
        rows: 8
  user-chris:
    db:  "db22"
    tables:
      t1:
        rows: 3
      t2:
        rows: 7
  user-mary:
    db:  "db78"
    tables:
      t1:
        rows: 2
      t2:
        rows: 10
  EOT

  flatlist = flatten([
    for ux_key, ux_val in yamldecode(local.nestedmap): [
      for tx_key, tx_val in ux_val.tables: {
        pfx = trimprefix(ux_key, "user-")
        #key = "${pfx}-${tx_key}"
        key = "${trimprefix(ux_key, "user-")}-${tx_key}"
        db = ux_val.db
        rows = tx_val.rows
      }
    ]
  ])
  flatmap = {for fx in local.flatlist:  fx.key => fx}
}
xbalaji
  • 982
  • 7
  • 16
  • "which doesn't work" - what does it mean? What errors do you get? – Marcin Feb 24 '22 at 06:11
  • $terraform validate ╷ │ Error: Invalid reference │ │ on loopvar.tf line 46, in locals: │ 46: key = "${pfx}-${tx_key}" │ │ A reference to a resource type must be followed by at least one attribute access, specifying the resource name. ╵ – xbalaji Feb 24 '22 at 06:29
  • There is no definition of `pfx` in your code. What is that? – Marcin Feb 24 '22 at 06:43
  • that is what my question is, how to use intermediate variables – xbalaji Feb 24 '22 at 06:45
  • @Marcin, thanks; you confirmed my observation – xbalaji Feb 26 '22 at 17:35
  • 1
    oops sorry, I was trying to find where I can click accept, I clicked the up vote button, sorry about that. I appreciate your time and your input. – xbalaji Feb 27 '22 at 23:30

2 Answers2

1

There are no intermediate variables in TF. You have to just repeat trimprefix(ux_key, "user-"):

  flatlist = flatten([
    for ux_key, ux_val in yamldecode(local.nestedmap): [
      for tx_key, tx_val in ux_val.tables: {
        pfx = trimprefix(ux_key, "user-")
        key = "${trimprefix(ux_key, "user-")}-${tx_key}"
        db = ux_val.db
        rows = tx_val.rows
      }
    ]
  ])
Marcin
  • 215,873
  • 14
  • 235
  • 294
0

For anyone interested in more discussions on this, have a look at - https://www.reddit.com/r/Terraform/comments/t03nfr/terraform_temporaryintermediate_variables_in_loops/

sharing here, so it is useful for others who are faced with similar question

xbalaji
  • 982
  • 7
  • 16