Terraform循环未执行:如何批量创建GitHub仓库?
Terraform 批量创建GitHub仓库配置方案
你可以通过Terraform的for_each或count参数实现批量创建GitHub仓库,以下是两种可行的配置写法:
方法一:使用for_each(推荐)
这种方式通过集合遍历创建资源,每个实例以仓库名称作为唯一标识,后续修改列表时不会无故重建其他资源:
# 定义仓库名称列表变量 variable "repo_names_list" { type = list(string) default = ["repo1", "repo2", "repo3"] } # 批量生成GitHub仓库资源 resource "github_repository" "repos" { # 将列表转为集合,用于for_each遍历 for_each = toset(var.repo_names_list) name = each.key # 直接使用当前遍历的仓库名称 visibility = "private" # 可添加其他通用配置,比如自动初始化仓库 auto_init = true }
方法二:使用count
通过列表长度控制资源数量,按索引获取仓库名称,适合不需要频繁调整列表顺序的场景:
variable "repo_names_list" { type = list(string) default = ["repo1", "repo2", "repo3"] } resource "github_repository" "repos" { # 资源实例数量等于列表长度 count = length(var.repo_names_list) name = var.repo_names_list[count.index] # 通过索引取对应名称 visibility = "private" auto_init = true }
说明
你之前的写法没有启用Terraform的批量资源创建机制,必须通过for_each或count参数触发循环逻辑,才能根据列表生成多个仓库资源。
内容的提问来源于stack exchange,提问作者stk1234
相关产品推荐
相关产品推荐

