如何将子模块的additional_tags传递至Terragrunt根配置的provider块?
实现通用标签与其他标签合并的方案
需求目标
从模块目录(如./non-production/eu-west-1/dev/eks-vpc/terragrunt.hcl)关联的_envcommon/[模块名].hcl文件中读取additional_tags,并与根目录terragrunt.hcl中的通用标签合并,最终注入到generate "provider"块的AWS默认标签中。
当前目录结构
├── README.md ├── _envcommon │ └── eks-vpc.hcl ├── non-production │ ├── account.hcl │ └── eu-west-3 │ ├── dev │ │ ├── eks-vpc │ │ │ └── terragrunt.hcl │ │ └── env.hcl │ ├── region.hcl └── terragrunt.hcl
解决方案
1. 修正模块目录的terragrunt.hcl关联路径
确保模块指向正确的_envcommon配置文件(以eks-vpc模块为例):
# ./non-production/eu-west-1/dev/eks-vpc/terragrunt.hcl include "root" { path = find_in_parent_folders() expose = true } # 关联对应模块的envcommon配置 include "envcommon"{ path = "${get_parent_terragrunt_dir()}/_envcommon/eks-vpc.hcl" expose = true } terraform { source = "${include.envcommon.locals.base_url}?ref=v1.0.0" } inputs = { # 其他输入值 }
2. 修改根目录terragrunt.hcl实现标签合并
在根配置中动态读取当前模块对应的_envcommon配置,合并通用标签与模块专属标签:
# ./terragrunt.hcl locals { account_vs = read_terragrunt_config(find_in_parent_folders("account.hcl")) environment_vs = read_terragrunt_config(find_in_parent_folders("env.hcl")) account_id = local.account_vs.locals.aws_account_id profile = "<aws_profile_name>" region = "eu-west-1" common_tags = { env = local.environment_vs.locals.environment controlledBy = "terraform" } # 动态获取当前模块名称,读取对应envcommon配置 module_name = basename(get_terragrunt_dir()) envcommon_config = read_terragrunt_config("${get_parent_terragrunt_dir()}/_envcommon/${local.module_name}.hcl") additional_tags = lookup(local.envcommon_config.locals, "additional_tags", {}) # 兼容无additional_tags的情况 # 合并通用标签与模块专属标签 tags = merge(local.common_tags, local.additional_tags) } generate "provider" { path = "provider.tf" if_exists = "skip" contents = <<EOF provider "aws" { region = "${local.region}" profile = "${local.profile}" allowed_account_ids = ["${local.account_id}"] default_tags { tags = ${jsonencode(local.tags)} } } EOF } remote_state { # 远程状态配置 }
3. _envcommon/eks-vpc.hcl保持原有配置
# ./envcommon/eks-vpc.hcl locals { additional_tags={ "Criticality" = "critical" "Supporting:Tools" = true } base_url = "你的模块仓库地址" # 补充实际地址 }
说明
- 该方案支持多模块场景,每个模块可关联
_envcommon下对应的配置文件,实现按模块注入不同的默认标签。 - 使用
lookup函数兼容部分模块无additional_tags的情况,避免执行报错。
内容的提问来源于stack exchange,提问作者joebegborg07
相关产品推荐
相关产品推荐

