带有嵌套资源的 Terraform for_each

时间:2021-04-28 07:07:07

标签: terraform terraform-provider-gcp terraform0.12+

我在本地使用 for_each,在 bigquery 中创建多个数据集。 另一个用于创建表的 for_each,在之前的数据集中。

问题是我必须使用 dataset_ressource.dataset_id.id 之类的数据集来引用表,但我使用 each.value.dataset1。

所以,它只有在我运行两次“terraform apply”时才有效

locals {
  bq_settings = {
    "${var.dataset1}" = {description = "description dataset 1"},
  } 
} 

locals {
  table_settings = {
    "${var.table1}" = {dataset_id = "dataset1_test", file = "table1.json"},
  } 
} 



resource "google_bigquery_dataset" "map" {
  for_each  = local.bq_settings
  dataset_id                  = each.key
  description                 = each.value.description
  location                    = var.location
  default_table_expiration_ms = 3600000
  
  labels = {
    env = "default"
  }
}

resource "google_bigquery_table" "map" {
  for_each  = local.table_settings

  dataset_id = each.value.dataset_id   
  table_id   = each.key
  deletion_protection = false

  time_partitioning {
    type = "DAY"
  }

  labels = {
    env = "default"
  }

  schema = file("${path.module}/schema-bq/${each.value.file}")
  
} 
```

1 个答案:

答案 0 :(得分:1)

它第二次起作用了,因为 google_bigquery_datasetgoogle_bigquery_table 之间没有直接关系。您可以使用 depends_on:

显式添加这样的关系
resource "google_bigquery_table" "map" {
  for_each  = local.table_settings

  dataset_id = each.value.dataset_id   
  table_id   = each.key
  deletion_protection = false

  time_partitioning {
    type = "DAY"
  }

  labels = {
    env = "default"
  }

  schema = file("${path.module}/schema-bq/${each.value.file}")

  depends_on = [google_bigquery_table.map]  
}