简体   繁体   中英

Iterate through a conditional for_each map of strings

Trying to put something together to get passed a limitation of the tfe plugin.

I have 200+ workspaces that I manage with a variable in Terraform Cloud that I need to update. All workspaces that I need to update start with "dev-workspace" in this case.

I have a data block with the following:

data "tfe_workspace_ids" "all" {
  names        = ["*"]
  organization = "myorganization"
}

I can't do a wildcard search for these workspaces due to a limitation of the module. This data block returns a map of strings that include all of my workspaces:

aa = {
    "dev-workspace-1"                   = "ws-anonymized"
    "dev-workspace-2"                   = "ws-ws-anonymized"
    "dev-workspace-3"                   = "ws-ws-anonymized"
    "test-workspace-1"                  = "ws-ws-anonymized"
    "prod-workspace-1"                  = "ws-ws-anonymized"
}

My problem is that I need to take this map of strings and filter it down to just return the ones that have "dev-workspace" in the key. I've tried something like the following:

resource "tfe_variable" "dev-workspace" {
  for_each = contains(data.tfe_workspace_ids.all.ids, "dev-workspace")

  key = "access_key"
  value = "XXXX"
  category = "terraform"
  workspace_id = each.value
  sensitive = true
  description = "AWS IAM secret access key."
}

But it doesn't look like you can use contains in this manner with for_each :

Error: Error in function call

  on main.tf line 16, in resource "tfe_variable" "dev-workspace":
  16:   for_each = contains(data.tfe_workspace_ids.all.ids, "dev-workspace")
    |----------------
    | data.tfe_workspace_ids.all.ids is map of string with 284 elements

Call to function "contains" failed: argument must be list, tuple, or set.

I'm not really sure what to do here, but have tried this several ways and can't figure it out. Thanks for any help.

If you want to filter, your resource could be (you have to change var.aa to the value of data.tfe_workspace_ids which produces the input map):


variable "aa" {

  default = {
      "dev-workspace-1"                   = "ws-anonymized"
      "dev-workspace-2"                   = "ws-ws-anonymized"
      "dev-workspace-3"                   = "ws-ws-anonymized"
      "test-workspace-1"                  = "ws-ws-anonymized"
      "prod-workspace-1"                  = "ws-ws-anonymized"
  }
}

resource "tfe_variable" "dev-workspace" {

  for_each = {for k, v in var.aa:
              k => v if length(regexall("dev-workspace", k)) > 0}

  key = "access_key"
  value = "XXXX"
  category = "terraform"
  workspace_id = each.value
  sensitive = true
  description = "AWS IAM secret access key."
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM