zkta
zkta

Reputation: 105

Terraform for_each with nested resources

I am using for_each with local, to create multiples dataset in bigquery. And another for_each to create table, in previous dataset.

The problem is I have to reference the table with dataset like dataset_ressource.dataset_id.id but I use each.value.dataset1.

So, it works only if I run "terraform apply" twice

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}")
  
} 
```

Upvotes: 1

Views: 683

Answers (1)

Marcin
Marcin

Reputation: 238877

It works second time, because there is no direct relationship between google_bigquery_dataset and google_bigquery_table. You can explicitly add such a relationship using 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]  
} 

Upvotes: 1

Related Questions