使用 for_each 语法帮助创建的资源中带有 for_each 的动态块

Dynamic block with for_each inside a resource created with for_each syntax assitance

当资源本身是使用 for_each 创建时,我正在尝试找到一种有条件地填充 github_repository 资源的页面块的方法。动态块似乎是实现此目的的合适方法,但我在语法上苦苦挣扎。

我试过下面的代码但失败了。

variables.tf:

variable "repositories" {
  description = "The repositories to create using terraform"
  type = list(object({
    name                 = string,
    description          = string,
    vulnerability_alerts = bool,
    pages_cname          = string
   }))
  }

terraform.tfvars.json:

{
  "repositories": [
    {
      "name": "repo-with-pages",
      "description": "Repository with pages enabled.",
      "vulnerability_alerts": true,
      "pages_cname": "www.example.com"
    },
    {
      "name": "repo-without-pages",
      "description": "Repository without pages enabled.",
      "vulnerability_alerts": true
    }
  ]
}

main.tf:

resource "github_repository" "this" {
  for_each               = { for repo in var.repositories : repo.name => repo }
  name                   = each.value.name
  description            = each.value.description
  vulnerability_alerts   = each.value.vulnerability_alerts

  dynamic "pages" {
    for_each = { for repo in var.repositories : repo.name => repo }
    content {
      source {
        branch = "main"
        path   = "/docs"
      }
      cname = each.value.pages_cname
      }
    }
  }
 

结果:

Error: Too many pages blocks

on main.tf line 43, in resource "github_repository" "this":
43:     content {

No more than 1 "pages" blocks are allowed

这很有意义,因为动态块中的 for 表达式 for_each return 有两个值(repo-with-pages 和 repo-without-pages)并且只允许 1 个页面块.因此,需要发生的是 for_each / for 表达式组合需要 return 1 值 - 创建的存储库的名称 - IF 页面已启用。

看了一段时间,开始怀疑我想做的事情是否可行,或者我是否把事情复杂化了。欢迎任何帮助。谢谢。

要使 pages_cname 可选,它应该是:

variable "repositories" {
  description = "The repositories to create using terraform"
  type = list(any)

然后

  dynamic "pages" {
    for_each = contains(keys(each.value), "pages_cname") ? [1] : []
    content {
      source {
        branch = "main"
        path   = "/docs"
      }
      cname = each.value.pages_cname
      }
    }
  }