[英]Terraform How to use for each values from one resource in another resource
I am trying to create users in terraform cloud based off a simple csv, structured like so:我正在尝试基于一个简单的 csv 在 terraform 云中创建用户,结构如下:
email,access_level
test@gmail.com,readonly
test2@gmail.come,owners
I can create users easily enough using the following resource block:我可以使用以下资源块轻松创建用户:
locals {
users_csv = csvdecode(file("${path.module}/users.csv"))
}
resource "tfe_organization_membership" "users_csv" {
for_each = { for r in local.users_csv : r.email => r }
organization = var.ppl_organisation
email = each.value.email
}
However, if I want to add them to teams then I need the "id" output from the above resource into the below resource:但是,如果我想将它们添加到团队中,那么我需要将上述资源的“id”输出到以下资源中:
resource "tfe_team_organization_member" "readonly_member" {
for_each = { for r in local.read_only : r.email => r }
team_id = each.value.access_level == "readonly" ? each.value.access_level : local.readonly_id
organization_membership_id = "${tfe_organization_membership.users_csv.id}"
}
Is there a way to pass this?有没有办法通过这个?
Thanks in advance.提前致谢。
I think the first thing I'd do here is to factor out the projection of your CSV data from a list to a map, like this:我想我在这里要做的第一件事是将 CSV 数据从列表到地图的投影分解出来,如下所示:
locals {
users_csv = csvdecode(file("${path.module}/users.csv"))
users = { for r in local.users_csv : r.email => r }
}
By defining local.users
like this we can make it more concise to refer to that value multiple times elsewhere in the config:通过像这样定义
local.users
我们可以更简洁地在配置中的其他地方多次引用该值:
resource "tfe_organization_membership" "users_csv" {
for_each = local.users
organization = var.ppl_organisation
email = each.value.email
}
resource "tfe_team_organization_member" "readonly_member" {
for_each = local.users
team_id = (
each.value.access_level == "readonly" ?
each.value.access_level :
local.readonly_id
)
organization_membership_id = tfe_organization_membership.users_csv[each.key].id
}
Any resource that has for_each
set is represented in expressions as a map of objects whose keys are the same as the for_each
input map, so the tfe_organization_membership.users_csv[each.key]
expression refers to an object representation of the corresponding instance of the other resource, correlating by the map keys.任何具有
for_each
集合的资源在表达式中表示为键与for_each
输入映射相同的对象映射,因此tfe_organization_membership.users_csv[each.key]
表达式指的是其他资源的相应实例的对象表示,通过地图键关联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.