如何访问连接块中计数 google_compute_instance 的 NAT IP?

How do I access the NAT IP of a counted google_compute_instance in a connection block?

我正在尝试使用 count = number 创建多个实例。在此期间,我需要访问已创建实例的 IP 地址,但无法循环访问属性。我的 Terraform 版本是 0.12.26.

我尝试了几种方法,但都没有。一切正常,直到我尝试通过 count.index 访问已创建实例的数量。这是代码:

resource "google_compute_instance" "test" {
  count        = 2
  name         = "test-${count.index}"
  
  # irrelevant stuff

  connection {
    host        = google_compute_instance.test.*.network_interface.0.access_config.0.nat_ip[count.index]
    
    # irrelevant stuff

我也试过这里的建议,但没有成功: How do I access an attribute from a counted resource within another resource?

根据我试过的那些帖子:

host = google_compute_instance.test[count.index].network_interface.0.access_config.0.nat_ip
host = element(google_compute_instance.test.*.network_interface.0.access_config.0.nat_ip, count.index)

每次我得到:

Error: Cycle: google_compute_instance.test[1], google_compute_instance.test[0]

如何在连接块中访问计数 google_compute_instance 的 NAT IP?

由于您有一个针对单个资源的自引用示例,因此这应该适用于计数的资源:

resource "google_compute_instance" "test" {
  count        = 2
  name         = "test-${count.index}"
  
  # irrelevant stuff

  connection {
    host        = self.network_interface.0.access_config.0.nat_ip
    
   # irrelevant stuff

The self Object

Expressions in connection blocks cannot refer to their parent resource by name. Instead, they can use the special self object.

The self object represents the connection's parent resource, and has all of that resource's attributes. For example, use self.public_ip to reference an aws_instance's public_ip attribute.

The self Object from the Provisioner Connection Settings docs.