如何在Terragrunt的before_hook中执行带||的Terraform workspace命令?
解决方案:通过Shell解释器执行逻辑命令
Terragrunt的execute参数为数组形式,无法直接识别Shell的逻辑运算符(如||),要实现“选不到工作区则新建”的逻辑,需通过调用Bash解释器来执行完整的Shell命令:
- 修改
before_hook的execute配置,将命令封装到bash -c中:
# root/terragrunt.hcl terraform { before_hook "workspace" { commands = ["plan", "apply", "destroy"] execute = [ "bash", "-c", "terraform workspace select ${local.environment} || terraform workspace new ${local.environment}" ] } }
- 关键原理说明:
bash -c会启动一个Bash进程,执行后续字符串中的完整Shell命令,这样就能正常解析||逻辑运算符${local.environment}会被Terragrunt插值为对应的环境变量值,确保命令动态适配不同环境
- 注意事项:
- 确保
local.environment变量已在当前配置中正确定义(比如通过locals块或外部输入) - 运行Terragrunt的环境需要具备Bash解释器(Linux/macOS默认自带,Windows需通过WSL或Git Bash等环境提供)
内容的提问来源于stack exchange,提问作者SLN
相关产品推荐
相关产品推荐

