Terraform - 循环文件夹以创建 n 个单独的资源

Pie*_*dre 2 google-cloud-platform terraform

我有一个文件夹queries,用户可以在其中添加、删除和修改yaml文件。每个 yaml 文件代表 GCP 上的单个 terraform 资源,即调度查询

循环查询文件夹并main.tf相应地在 main 中生成适当数量的 terraform 资源的最干净方法是什么?我可以使用Python来生成main.tf如果它更容易

1 个信号资源的示例:

查询/alpha.yaml

display_name: "my-query"
data_source_id: "scheduled_query"
schedule: "first sunday of quarter 00:00"
destination_dataset_id: "results"
destination_table_name_template: "my_table"
write_disposition: "WRITE_APPEND"
query: "SELECT name FROM tabl WHERE x = 'y'"
Run Code Online (Sandbox Code Playgroud)

这应该在我的main.tf中创建这个资源

resource "google_bigquery_data_transfer_config" "query_config" {
  display_name           = "my-query"
  data_source_id         = "scheduled_query"
  schedule               = "first sunday of quarter 00:00"
  destination_dataset_id = "results"
  params = {
    destination_table_name_template = "my_table"
    write_disposition               = "WRITE_APPEND"
    query                           = "SELECT name FROM tabl WHERE x = 'y'"
  }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*cin 7

您可以阅读以下目录中的所有文件locals

locals {
  
   query_files = fileset(path.module, "queries/*.yaml")
   
   queries = {for query_file in local.query_files: 
              query_file => yamldecode(file(query_file))}
}
Run Code Online (Sandbox Code Playgroud)

然后用于for_each创建您的资源:

resource "google_bigquery_data_transfer_config" "query_config" {

  for_each               = local.queries

  display_name           = each.value.display_name
  data_source_id         = each.value.data_source_id
  schedule               = each.value.schedule
  destination_dataset_id = each.value.destination_dataset_id
  params = {
    destination_table_name_template = each.value.destination_table_name_template
    write_disposition               = each.value.write_disposition
    query                           = each.value.query
  }
}
Run Code Online (Sandbox Code Playgroud)