amazon-web-servicesterraformtaggingterragrunt

How to get a relative path of terragrunt.hcl in an AWS resource's tag?


How can I tag each AWS resource with a relative path of its source/terragrunt.hcl file? Ideally, the solution, if it exists, would also work with a locally/relatively referenced modules (rather than only modules from a 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
}

The error on terragrunt apply, with the root terragrunt.hcl as above:

> 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

Solution

  • Got the relative path added as a tag, by simplifying the 1st snippet in the question:

    # 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
    }
    

    The nested replace functions could use some simplification.