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

如何让Terragrunt缓存包含顶层monitor目录?

问题描述

我是Terragrunt新手,遇到了缓存相关的问题。我的文件结构如下:

├── monitor
│   └── files
│       └── graph
│           └── server
│               └── default
│                   └── foo.json
└── terraform
    ├── env
    │   └── stage
    │       └── cluster
    │           ├── provider.tf
    │           └── terragrunt.hcl
    ├── moduleConfig
    │   └── cluster
    │       ├── backend.tf
    │       ├── random.tf
    │       ├── locals.tf
    │       ├── outputs.tf
    │       ├── main.tf
    │       ├── outputs.tf
    │       └── variables.tf
    └── terragrunt.hcl

当我在env/stage/cluster目录下运行terragrunt plan后,查看.terragrunt-cache文件夹,发现缓存中没有monitor目录:

.terragrunt-cache/
└── KdPWtxpAXZdCe4otk2N9TY1tuQU
    └── cwMVo-pYTWr47TeiHN8aORnD8g4
        ├── env
        │   └── stage
        │       └── cluster
        │           ├── provider.tf
        │           └── terragrunt.hcl
        ├── moduleConfig
        │   └── cluster
        │       ├── backend.tf
        │       ├── random.tf
        │       ├── locals.tf
        │       ├── outputs.tf
        │       ├── main.tf
        │       ├── outputs.tf
        │       ├── provider.tf
        │       ├── terragrunt.hcl
        │       └── variables.tf
        └── terragrunt.hcl

这导致plan输出不符合预期,因为我需要用到monitor目录中的资源。我的配置块如下:

include {
  path = find_in_parent_folders()
}
terraform {
  source = "${path_relative_from_include()}//moduleConfig/cluster"
}

请问有没有办法让Terragrunt将monitor目录也包含进来,使缓存包含我需要的完整文件树?

解决方案

Terragrunt默认只会复制与Terraform模块、配置相关的文件到缓存目录,要让它纳入额外目录或解决资源访问问题,可通过以下两种方式实现:

方法1:用extra_arguments指定工作目录(推荐)

无需修改缓存结构,直接让Terraform在包含monitor的根目录运行,这样模块就能直接访问monitor下的资源。

修改env/stage/cluster/terragrunt.hcl,添加如下配置块:

extra_arguments "set_root_workdir" {
  commands = get_terraform_commands_that_need_vars()

  arguments = [
    "-chdir=${get_parent_terragrunt_dir()}/../"
  ]
}

该配置会让Terraform在monitor和terraform的共同父目录执行,你的模块就能正常引用monitor/files/...路径下的资源。

方法2:配置copy_modules_on_install复制额外目录

如果一定要将monitor目录复制到缓存中,可在根目录的terraform/terragrunt.hcl里添加如下配置:

copy_modules_on_install {
  include = ["../monitor/**"]
}

路径../monitor是相对于根terragrunt.hcl(位于terraform目录下),**表示包含该目录下所有文件及子目录,执行Terragrunt命令时会自动将monitor目录复制到缓存内。

补充说明

  • 方法1更简洁,避免了缓存目录结构的修改,也减少了路径引用混乱的概率。
  • 若你通过file()等Terraform函数引用monitor下的文件,确保路径与-chdir指定的目录相对应,尽量避免使用绝对路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 16:48:21