错误 - 缺少资源实例键:由于google_compute_instance设置了"count",因此必须在特定实例上访问其属性



我正在尝试传递在模块"中创建的谷歌计算实例的mat_ip;微服务实例";到另一个模块";数据库";。由于我正在创建多个实例,所以模块"中的输出变量出现以下错误;微服务实例";。

Error: Missing resource instance key
on modules/microservice-instance/ms-outputs.tf line 3, in output "nat_ip":    3:   value = google_compute_instance.apps.network_interface[*].access_config[0].nat_ip
Because google_compute_instance.apps has "count" set, its attributes must be accessed on specific instances.
For example, to correlate with indices of a referring resource, use:
google_compute_instance.apps[count.index]

我已经研究过以下内容,并使用相同的方式访问属性,但它不起作用。这是代码-主.tf

provider "google" {
credentials = "${file("../../service-account.json")}"
project = var.project
region =var.region

}
# Include modules
module "microservice-instance" {
count = var.appserver_count
source = "./modules/microservice-instance"
appserver_count = var.appserver_count
}
module "database" {
count  = var.no_of_db_instances
source = "./modules/database"
nat_ip = module.microservice-instance.nat_ip
no_of_db_instances = var.no_of_db_instances
}

/模块/微服务实例/微服务示例.tf

resource "google_compute_instance" "apps" {
count        = var.appserver_count
name         = "apps-${count.index + 1}"
# name         = "apps-${random_id.app_name_suffix.hex}"
machine_type = "f1-micro"
boot_disk {
initialize_params {
image = "ubuntu-os-cloud/ubuntu-1804-lts"
}
}
network_interface {
network = "default"
access_config {
// Ephemeral IP
}
}
}

/模块/微服务实例/ms-outputs.tf

output "nat_ip" {
value = google_compute_instance.apps.network_interface[*].access_config[0].nat_ip
}

/模块/数据库/数据库.tf

resource "random_id" "db_name_suffix" {
byte_length = 4
}
resource "google_sql_database_instance" "postgres" {
name             = "postgres-instance-${random_id.db_name_suffix.hex}"
database_version = "POSTGRES_11"
settings {
tier = "db-f1-micro"
ip_configuration {
dynamic "authorized_networks" {
for_each = var.nat_ip
# iterator = ip
content {
# value = ni.0.access_config.0.nat_ip
value = each.key
}
}
}
}
}

您正在创建var.appserver_count数量的google_compute_instance.apps资源。所以你会有:

google_compute_instance.apps[0]
google_compute_instance.apps[1]
...
google_compute_instance.apps[var.appserver_count - 1]

因此,在您的output中,而不是:

output "nat_ip" {
value = google_compute_instance.apps.network_interface[*].access_config[0].nat_ip
}

您必须使用[*]引用单个apps资源或所有资源,例如:

output "nat_ip" {
value = google_compute_instance.apps[*].network_interface[*].access_config[0].nat_ip
}

最新更新