[英]Terraform - how to use for_each loop on a list of objects to create resources
[英]how to add an additional loop over a stringlist within a for_each
我已經在 my.tf 配置中設置了多個 github 存儲庫,並在“github”存儲庫資源上使用了一個簡單的 for_each。 此外,我嘗試為每個新創建的回購創建幾個分支(每個環境一個分支)。
我的第一個意圖是使用一個模塊(./modules/github_repo/repo.tf),其中包括
locals {
environments = var.environments
}
resource "github_branch" "branches" {
for_each = toset(setsubtract(local.environments, ["prod"]))
repository = "orgName/${var.REPO_NAME}"
branch = lookup(var.environment_to_branch_map, each.key, each.key)
source_branch = "master"
}
具有以下變量
variable "REPO_NAME" {
type = string
}
variable "environments" {
type = list(string)
}
variable "environment_to_branch_map" {
type = map(any)
default = {
"prod" = "master"
"dev" = "develop"
}
從 main.tf 這樣調用
provider "github" {
token = var.GITHUB_TOKEN
owner = "orgName"
}
locals {
environments = ["dev", "prod", "staging", "test"]
microServices = tomap({ "service1" : "fnApp", "service2" : "fnApp" })
default_branch = "master"
}
module "branches_per_microservice" {
for_each = local.microServices
source = "./modules/github_repo"
REPO_NAME = each.key
environments = local.environments
depends_on = [github_repository.microservices]
}
不幸的是,我為每個分支和回購組合得到一個 404,就像這樣
錯誤:查詢 GitHub 分支參考 /orgName/service1 (refs/heads/master) 時出錯:GET https://api.github.com/repos//orgName/service1/git/ref/heads/master : 404 Not Found []使用 module.branches_per_microservice["service1"].github_branch.branches["test"] 在 modules/github_repo/repo.tf 第 23 行,在資源“github_branch”“branches”中:
我想這是一個“提供者”的東西,因為如果我嘗試直接在 main.tf 中創建一個分支,它就會起作用。 但問題是,我只能在一個資源中使用一個循環。 (我已經知道在帶有 count 或 for_each 循環的模塊中提供程序是不可能的,如 terraform 文檔中所寫)
resource "github_branch" "branches" {
for_each = toset(setsubtract(local.environments, ["prod"]))
repository = github_repository.microservices["service1"].name
branch = lookup(var.environment_to_branch_map, each.key, each.key)
source_branch = "master"
}
在這種情況下,我必須手動為每個“微服務”創建一個資源,我想極力避免這種情況……有沒有什么想法可以“嵌套”環境中的第二個循環來為每個微服務回購創建我的分支?
對於這里的任何提示、想法或方法,請提前致謝......
嵌套循環可以用兩個集合的setproduct
上的單個循環代替。 setproduct
的文檔可以在這里找到https://www.terraform.io/language/functions/setproduct
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.