我可以在 Terraform 中查找父资源的属性吗?

Can I look up attributes of a parent resources in Terraform?

上下文:我正在使用 SDKv2 开发新的 TF 提供程序。

假设有 3 个资源(“org”、“department”、“team”资源,它们通过 ID 相互引用):

resource "org" "foo" {
   name   = "abc"
   height = "5"
}

resource "department" "bar" {
   org_id = org.foo.id
   name   = "xyz"
   weight = "5"
}

resource "team" "qqq" {
   org_id = org.foo.id
   department_id = department.foo.id
   age = "10"
}

当前的设置对我们来说工作正常,但现在我们正在考虑添加另一个 employee 资源,该资源必须引用所有其他 3 个资源。

resource "employee" "abc" {
   org_id = org.foo.id
   department_id = department.foo.id
   team_id = team.qqq.id
   name = "abc"
   org_name = org.foo.name
}

更糟糕的是,他们需要引用 org.name 所以我们认为引用太多了。

有没有一种方法可以让我们以编程方式遍历 TF 状态,或者允许我们仅引用 team.qqq 并推断所有这些 org_iddepartment_id 等的方法?

resource "employee" "abc" {
   team_id = team.qqq.id # somehow iterate over TF state, find team.qqq.id = team_id and infer org_id and department_id
   name = "abc"
}

扩展我的评论:

你的代码看起来不错我见过最差的...
我真的没有看到太多的参考,看这个例子:
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/route53_record#alias-record

resource "aws_route53_record" "www" {
  zone_id = aws_route53_zone.primary.zone_id
  name    = "example.com"
  type    = "A"

  alias {
    name                   = aws_elb.main.dns_name
    zone_id                = aws_elb.main.zone_id
    evaluate_target_health = true
  }
}

...很常见


老实说,我和你一样痛苦,我们这些习惯面向对象编程的人对 terraform 很生气,理想情况下我们传递对整个对象的引用并让资源使用它需要的东西,如果我要构建它,结果代码可能类似于:

resource "org" "foo" {
   name   = "abc"
   height = "5"
}

resource "department" "bar" {
   org    = org.foo
   name   = "xyz"
   weight = "5"
}

resource "team" "qqq" {
   department = department.bar
   age        = "10"
}

resource "employee" "abc" {
   team = team.qqq
   name = "abc"
}

并且从员工属性我们可以知道它所属的组织、部门或团队的所有信息:

  • employee.abc.team.department.org.name
  • employee.abc.team.department.weight
  • employee.abc.team.age

但祝你在 TF 提供程序中实现它好运