根据相同的键将资源分配给另一个资源

Assign resources to another resource based on same key

我有两个变量如下:

servers = {
  server1 = {
    name   = "Server1"
    project = "Development"
  },
  server2 = {
    name   = "Server2"
    project = "Staging"
  }
}

projects = {
  project1 = {
    name        = "Project Development"
    environment = "Development"
  },
  project2 = {
    name        = "Project Staging"
    environment = "Staging"
  }
}

我正在创建服务器并希望根据 project/environment link.

将服务器分配给项目资源
resource "instance" "server" {
  for_each = var.servers
  name   = each.key
}


resource "project" "project" {
  for_each = var.projects 

  name        = each.value.name
  resources   = values(instance.server)[*].urn
}

使用上面的代码,项目创建成功,所有服务器被分配给最后创建的项目。

我正在寻找一种仅循环遍历“开发”项目并分配 项目处于“开发”(与“暂存”相同)的服务器的方法。

注意:我知道我可以创建一个嵌套变量如下:

projects = {
  project1 = {
    name        = "Project Development"
    environment = "Development"
    servers = {
      server1 = {
        name   = "Server1"
        project = "Development"
      }
    }
  },
  project2 = {
    name        = "Project Staging"
    environment = "Staging"
    servers = {
      server2 = {
        name   = "Server2"
        project = "Staging"
      }
    }
  }
}

然后展平这个结构,但这不是我现在想要的。

更新 1

我尝试了以下方法:

resource "project" "project_development" {
  #for_each = var.projects 

  for_each = {
   for key, value in var.projects : key => value
      if value.environment == "Development"
}

  name        = each.value.name
  description = each.value.description
  purpose     = each.value.purpose
  environment = each.value.environment

  resources = values(instance.server)[*].urn
}

resource "project" "project_staging" {
  #for_each = var.projects 

  for_each = {
   for key, value in var.projects : key => value
      if value.environment == "Staging"
}

  name        = each.value.name
  description = each.value.description
  purpose     = each.value.purpose
  environment = each.value.environment

  resources = values(instance.server)[*].urn
}

但所有资源最终仍属于 1 个项目,这与 values(instance.server)[*].urn 相关,它采用所有已创建的实例。

您可以尝试以下方法

for_each = {
   for key, value in var.projects : key => value
      if value.environment == "Development"
}

通过这种方式循环的对象必须具有开发环境

更新 1

resources = [ for key, value in var.servers : instance.server[key].urn
    if value.project == "Development"
]

我们可以通过过滤、应用上述逻辑来获取服务器的 urn