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

如何在Terragrunt中通过环境变量动态读取YAML配置值?

解决Terragrunt动态获取环境配置的问题

问题根源

Terragrunt基于HCL语法,不支持嵌套插值表达式(比如${local.env_vars.${get_env("TF_VAR_ENV_NAME")}.vpc_id}这种写法),必须使用方括号索引语法来动态访问对象的键。

可行解决步骤

  1. 确保YAML加载与环境变量获取正确
    在terragrunt.hcl里定义本地变量,完成配置文件加载和环境变量获取:

    locals {
      # 加载environment.yaml中的环境配置
      env_vars = yamldecode(file("environment.yaml"))
      # 获取GitHub Actions传入的环境变量,设置默认值避免空值报错
      current_env = get_env("TF_VAR_ENV_NAME", "sandpit")
    }
    
  2. 用方括号索引动态获取配置
    替换错误的嵌套插值写法,改用索引方式访问对应环境的配置项:

    # 正确获取当前环境的vpc_id
    local.env_vars[local.current_env].vpc_id
    # 同理获取acc_id
    local.env_vars[local.current_env].acc_id
    

完整示例

environment.yaml内容

sandpit:
  vpc_id: vpc-123456
  acc_id: 123456789012
nonprod:
  vpc_id: vpc-654321
  acc_id: 210987654321

terragrunt.hcl使用示例

locals {
  env_vars = yamldecode(file("environment.yaml"))
  current_env = get_env("TF_VAR_ENV_NAME", "sandpit")

  # 可选:校验当前环境是否在配置中存在,避免非法值导致报错
  env_exists = contains(keys(local.env_vars), local.current_env)
}

# 示例:在依赖模块中传入动态获取的参数
dependency "vpc" {
  config_path = "../vpc-module"

  inputs = {
    vpc_id      = local.env_vars[local.current_env].vpc_id
    account_id  = local.env_vars[local.current_env].acc_id
  }
}

# 可选:如果环境不存在,强制终止并提示错误
run_cmd("echo 'Invalid environment: ${local.current_env}' && exit 1", condition = !local.env_exists)

额外注意事项

  • 确认GitHub Actions中TF_VAR_ENV_NAME环境变量已正确传递给Terragrunt,比如在作业的env块中明确设置
  • 给get_env设置默认值,能避免环境变量未传入时出现空值问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 17:45:21