【问题标题】:Pattern for templating arguments for existing Terraform resources为现有 Terraform 资源模板化参数的模式
【发布时间】:2020-05-29 10:56:19
【问题描述】:

我正在使用 Terraform GitHub 提供程序为内部 GitHub Enterprise 实例定义 GitHub 存储库(尽管问题不是特定于提供程序的)。

现有的github_repository 资源工作正常,但我希望能够为其某些参数设置非标准默认值,并轻松地将其他参数分组到一个新参数下。

例如

  • github_repositoryprivate 值默认为 false 但我想默认为 true
  • 许多 repos 只希望允许 squash 合并,因此有一个 squash_merge_only 参数来设置 allow_squash_merge = true, allow_rebase_merge = false, allow_merge_commit = false

还有更多案例,但这些案例说明了这一点。目的是让人们更容易正确配置新的 repos,并避免在每个 repo 中重复大量配置。

我可以通过将变量传递到自定义模块来实现这一点,例如类似于:

Foo/custom_repo/main.tf:

resource "github_repository" "custom_repo" {
  name                 = ${var.repo_name}
  private              = true
  allow_squash_merge   = true
  allow_merge_commit   = ${var.squash_merge_only ? false : true}
  allow_rebase_merge   = ${var.squash_merge_only ? false : true}
} 

Foo/main.tf:

provider "github" {
 ...
}

module "MyRepo_module" {
  source            = "./custom_repo"
  repo_name         = "MyRepo"
  squash_merge_only = true
}

虽然这有点垃圾,因为我必须为 github_repository 上的每个其他参数添加一个变量,使用 custom_repo 模块的人可能想要设置(这基本上是所有这些 - 我没有尝试限制人们被允许做的事情) - 参见示例中的namerepo_name。然后这一切都需要单独记录,鉴于现有提供者有很好的文档,这也是一种耻辱。

有没有更好的模式来重用这样的现有资源,但可以控制参数如何传递给它们?

【问题讨论】:

  • 在不为每个 repo 重复配置方面,您可以为一个资源中的每个 repo 使用带有迭代器的 Map 输入。就编写自定义模块然后必须指定所有可能的参数而言,您无法避免这样做。但是,实际上没有办法进一步简化它,因为它已经是一种资源。为一种资源配置输入的难度与为一种资源配置模块的难度是相当的。
  • 对于地图,你的意思是这样的吗? stackoverflow.com/a/57995310/2066474

标签: terraform terraform-provider-github


【解决方案1】:

我们为此在https://github.com/mineiros-io/terraform-github-repository创建了一个自以为是的模块(terraform 0.12+)

我们将所有默认值设置为我们认为最合适的值,但基本上您可以创建一组本地默认值并在多次调用模块时重用它们。

有趣的事实...您想要的默认值已经是模块的默认值,但是要清楚如何在此处明确设置这些是一个示例(未经测试):

locals {
  my_defaults = {
     # actually already the modules default to create private repositories
     private = true

     # also the modules default already and 
     # all other strategies are disabled by default
     allow_squash_merge = true
  }
}


module "repository" {
  source  = "mineiros-io/repository/github"
  version = "0.4.0"

  name = "my_new_repository"

  defaults = local.my_defaults
}

并非所有参数都被支持为默认值,但大多数是:https://github.com/mineiros-io/terraform-github-repository#defaults-object-attributes

【讨论】:

    猜你喜欢
    • 2020-09-27
    • 2021-03-13
    • 2018-08-01
    • 1970-01-01
    • 2021-04-17
    • 2022-09-22
    • 2021-02-15
    • 2021-05-15
    • 2023-02-23
    相关资源
    最近更新 更多