You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform条件遍历:仅当对象含指定属性时配置GitHub仓库变量与密钥

解决方案:仅当仓库包含指定属性时配置GitHub Actions变量/密钥

当然可行,你可以通过Terraform的for表达式结合lookup函数,筛选出包含variables或secrets属性的仓库,并遍历其中的列表项来创建对应的资源。

修正后的代码示例

首先修正locals.tf里的语法错误("CLIENTSECRET缺少闭合引号):

locals {
  repos = {
    "terraform-tfe" : {
      description        = "Automation for Terraform Cloud"
      visibility         = "private"
    }
    "terraform-github" : {
      description        = "Automation for Github Repos"
      visibility         = "private"
    }
    "terraform-testapp" : {
      description        = "Test web app "
      visibility         = "private"
      variables = ["STORAGEACCOUNT","HOSTURL"]
      secrets   = ["CLIENTID", "CLIENTSECRET"] # 修正引号缺失问题
    }
  }
}

然后修改main.tf中的资源定义,实现按需创建:

resource "github_repository" "repos" {
  for_each = local.repos

  name        = each.key
  description = each.value.description
  visibility  = each.value.visibility
}

# 创建GitHub Actions变量:仅处理包含variables属性的仓库
resource "github_actions_variable" "repository_variables" {
  # 遍历所有仓库的variables列表,生成唯一键:仓库名-变量名
  for_each = {
    for repo_name, repo in local.repos :
    "${repo_name}-${var_name}" => {
      repo_name = repo_name
      var_name  = var_name
    }
    for var_name in lookup(repo, "variables", []) # 无variables属性时返回空列表,跳过
  }

  repository = each.value.repo_name
  name       = each.value.var_name
  value      = var[each.value.var_name] # 假设你在根变量里定义了这些变量的值
}

# 创建GitHub Actions密钥:仅处理包含secrets属性的仓库
resource "github_actions_secrets" "repository_secrets" {
  # 遍历所有仓库的secrets列表,生成唯一键:仓库名-密钥名
  for_each = {
    for repo_name, repo in local.repos :
    "${repo_name}-${secret_name}" => {
      repo_name = repo_name
      secret_name  = secret_name
    }
    for secret_name in lookup(repo, "secrets", []) # 无secrets属性时返回空列表,跳过
  }

  repository      = each.value.repo_name
  secret_name     = each.value.secret_name
  plaintext_value = var[each.value.secret_name] # 假设根变量里定义了这些密钥的值
}

关键说明

  • lookup(repo, "variables", []):如果当前仓库对象没有variables属性,就返回空列表,对应的仓库会被跳过,不会生成资源。
  • 用"${repo_name}-${var_name}"作为for_each的键,确保每个变量/密钥的组合都是唯一的,符合Terraform对for_each键的唯一性要求。
  • 代码中假设你已经在Terraform根变量(比如variables.tf)中定义了对应的变量和密钥值,你可以根据实际情况调整value和plaintext_value的来源(比如从环境变量、Vault等读取)。

内容的提问来源于stack exchange,提问作者Omar Stewey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 18:30:11