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

chr*_*are 5 terraform terraform0.12+

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

我尝试使用下面的代码但失败了。

变量.tf:

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

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
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

主要.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
      }
    }
  }
 
Run Code Online (Sandbox Code Playgroud)

结果:

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
Run Code Online (Sandbox Code Playgroud)

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

我已经关注这个问题有一段时间了,并开始怀疑我想做的事情是否可能,或者我是否使事情过于复杂化。非常欢迎任何帮助。谢谢。

Mar*_*cin 2

要使其pages_cname可选,它应该是:

variable "repositories" {
  description = "The repositories to create using terraform"
  type = list(any)
Run Code Online (Sandbox Code Playgroud)

然后

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