如何在 AWS 资源的标签中获取 terragrunt.hcl 的相对路径?



如何用其源/terragrunt.hcl文件的相对路径标记每个AWS资源?理想情况下,该解决方案(如果存在(还将与本地/相对引用的模块(而不仅仅是来自git repo的模块(一起工作。

# In root terragrunt.hcl
locals {
# ...
aws_default_tags = jsonencode({  # This is line 48 in the error below.
ManagedBy = "Terraform"
TerraformBasePath = path.cwd  # What is a (working) equivalent of this?
)}
}
generate "provider" {
# ...
contents  = <<EOF
provider "aws" {
# ...
default_tags {
tags = jsondecode(<<INNEREOF
${local.aws_default_tags}
INNEREOF
)
}
}
EOF
}

terragrunt apply上的错误,根terragrunt.hcl如上所述:

> terragrunt apply 
ERRO[0000] Not all locals could be evaluated:           
ERRO[0000]      - aws_default_tags [REASON: Can't evaluate expression at 
/project/terragrunt.hcl:48,22-60,5: 
you can only reference other local variables here, 
but it looks like you're referencing something else (path is not defined)] 
ERRO[0000] Could not evaluate all locals in block.      
ERRO[0000] Unable to determine underlying exit code, so Terragrunt
will exit with error code 1

通过简化问题中的第一个片段,将相对路径添加为标签:

# In root terragrunt.hcl
locals {
# ...
# terraform-git-repo = "infrastructure"  # For future use in CD pipeline.
terraform-git-repo = "/local/path/infra"
}
generate "provider" {
# ...
contents  = <<EOF
provider "aws" {
# ...
default_tags {
tags = {
Terraform-base-path = replace(replace(path.cwd, "${local.terraform-git-repo}", ""), "/.terragrunt-cache/.*/", "")
}
}
}
EOF
}

嵌套的replace函数可以使用一些简化。

最新更新