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

Windows10下Terraform External Provider调用bash脚本提示jq命令未找到

解决Terraform External Provider调用bash脚本时jq找不到的问题

问题场景

Windows10机器上通过Chocolatey安装了jq,编写Terraform配置调用bash脚本simple.sh实现External Provider逻辑,脚本中用jq格式化输出,但执行Terraform时提示./simple.sh: line 4: jq: command not found。此前PowerShell实现的External Provider示例可正常运行,切换到Git Bash后该bash脚本也能正常工作。

相关配置及脚本

Terraform配置(main.tf):

provider "azurerm" {
  features {}
}

data "external" "simple-jq-test" {
  program = ["bash", "./simple.sh"]
}

bash脚本(simple.sh):

#!/bin/bash

function produce_output() {
  jq -n --arg arg1 "arg 1" '{"arg1":$arg1}'
}

produce_output

错误信息

data.external.simple-jq-test: Reading...
╷
│ Error: External Program Execution Failed
│
│   with data.external.simple-jq-test,
│   on main.tf line 8, in data "external" "simple-jq-test":
│    8:   program = ["bash", "./simple.sh"]
│
│ The data source received an unexpected error while attempting to execute the program.
│
│ Program: C:\Windows\system32\bash.exe
│ Error Message: ./simple.sh: line 4: jq: command not found
│
│ State: exit status 127
╵

原因分析

Terraform默认调用的是Windows系统自带的C:\Windows\system32\bash.exe(属于WSL环境),而通过Chocolatey安装的jq仅添加到Windows系统的PATH环境变量中,WSL的bash环境无法识别Windows的PATH,因此找不到jq命令。而Git Bash基于MinGW环境,会自动继承Windows的PATH配置,所以脚本在Git Bash中可以正常运行。

解决方案

方案1:改用Git Bash的bash执行脚本

修改Terraform配置中的program参数,指定Git Bash的bash.exe路径(默认安装路径为C:\Program Files\Git\bin\bash.exe):

data "external" "simple-jq-test" {
  program = ["C:\\Program Files\\Git\\bin\\bash.exe", "./simple.sh"]
}

这样Terraform会调用Git Bash执行脚本,继承Windows的PATH,就能找到Chocolatey安装的jq。

方案2:在WSL环境中安装jq

如果要继续使用Windows自带的bash.exe(WSL),可以打开WSL终端,通过包管理器安装jq。以Ubuntu为例:

sudo apt update && sudo apt install jq -y

安装完成后,WSL的bash环境就能直接识别jq命令。

方案3:在脚本中指定jq的绝对路径

找到Chocolatey安装jq的绝对路径(通常为C:\ProgramData\chocolatey\bin\jq.exe),在WSL环境中该路径对应/mnt/c/ProgramData/chocolatey/bin/jq.exe,修改脚本中的jq调用:

function produce_output() {
  /mnt/c/ProgramData/chocolatey/bin/jq.exe -n --arg arg1 "arg 1" '{"arg1":$arg1}'
}

直接指定jq的WSL格式路径,无需修改环境变量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 08:54:22