在开发 TF 提供程序时,我可以在 readResource() 中遍历 main.tf 中的其他资源吗?

Can I iterate through other resources in main.tf in readResource() when developing a TF provider?

上下文:我正在开发一个 TF 提供程序(这是来自 HashiCorp 的官方guide)。

我运行进入如下情况:

# main.tf
resource "foo" "example" {
   id = "foo-123"
   name = "foo-name"
   lastname = "foo-lastname"
}

resource "bar" "example" {
   id = "bar-123"
   parent_id = foo.example.id
   parent_name = foo.example.name
   parent_lastname = foo.example.lastname
}

我必须明确声明 parent_nameparent_lastname(有效地复制它们)才能读取这些值,这些值对于 Bar 资源的读取/创建请求是必需的。

是否可以在

中使用d *schema.ResourceData的花哨技巧
func resourceBarRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {

为了避免在我的 TF 配置中重复,即:

resource "foo" "example" {
   id = "foo-123"
   name = "foo-name"
   lastname = "foo-lastname"
}

resource "bar" "example" {
   id = "bar-123"
   parent_id = foo.example.id
}

仅根据 resourceBarRead() 中的 foo.example.id 以某种方式推断出 foo.example.namefoo.example.lastname,这样我就不必在两个资源中重复这些字段了?

显然,这是最小的示例,假设我需要 foo.example.namefoo.example.lastname 来发送对 Bar 资源的读取/创建请求?换句话说,我可以根据目标 ID 遍历 TF state / main.tf 文件中的其他资源来找到它的其他属性吗?它似乎是一个有用的功能,但是它没有在 HashiCorp 的指南中提到,所以我想它是不可取的,我必须复制这些字段。

在 Terraform 的 provider/resource 模型中,每个 resource 块都独立于所有其他块,除非用户像您展示的那样使用引用显式连接它们。

但是,在大多数提供程序中,仅向下游传递 id(或类似的唯一标识符)属性就足以创建这样的关系,因为有关该对象的其他信息已为远程系统所知.

在不了解您正在与之交互的特定远程系统的情况下,我希望您能够直接在 API 调用中使用作为 parent_id 给出的值(因此让远程系统将其与现有对象连接),或者向远程 API 发出额外的读取请求,以使用该 ID 查找对象并获取 namelastname 值之前保存的。

如果这些值只存在于提供者的上下文中而不存在于远程 API 那么我认为除了让用户再次传递它们之外别无选择,因为这是唯一的本地值(与远程 API 中持久存在的值相对)可以在资源之间传输的方式。