Terraform local-exec执行PowerShell提示可执行文件不在PATH如何解决
报错信息
运行命令
powershell -file ./main.ps1时出错:exec: "PowerShell":可执行文件未在$PATH中找到。
问题场景
在Azure DevOps Pipeline中运行Terraform时,需要通过PowerShell脚本完成部分配置,编写的null_resource与local-exec provisioner配置如下:
resource "null_resource" "terraform-script" { provisioner "local-exec" { command = "powershell -file ./main.ps1" interpreter = ["PowerShell", "-Command"] } depends_on = [ azurerm_resource_group.rg, azurerm_kubernetes_cluster.kc ] }
所有tf配置文件与PowerShell脚本main.ps1存放在同一目录下,执行时触发上述路径相关报错。
错误根因
- 解释器文件名配置错误:Linux/macOS系统对文件名大小写敏感,Azure DevOps的Ubuntu托管代理默认预装的PowerShell可执行文件名为
pwsh,Windows代理下的可执行文件名为小写的powershell.exe,配置中大写开头的PowerShell无法被系统识别,直接触发“可执行文件未在$PATH中找到”的报错。 - 执行参数逻辑冲突:interpreter中指定了
-Command参数,该参数会将后续传入的内容作为PowerShell命令字符串解析,与command中调用脚本的-file参数逻辑互斥,即使解决了路径问题也无法正常执行脚本。 - 相对路径不可靠:Terraform执行local-exec provisioner时的工作目录为Terraform运行时的当前工作目录,并非tf配置文件所在目录,直接写
./main.ps1的相对路径大概率会出现找不到脚本的问题。
修复方案
使用跨平台兼容的配置替换原有内容,修正后的配置如下:
resource "null_resource" "terraform-script" { provisioner "local-exec" { # 通过path.module内置变量获取当前模块的绝对路径,彻底解决路径定位问题 command = "${path.module}/main.ps1" # 统一使用跨平台的pwsh解释器,添加非交互参数适配Pipeline运行环境,指定-File参数执行脚本 interpreter = ["pwsh", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File"] } depends_on = [ azurerm_resource_group.rg, azurerm_kubernetes_cluster.kc ] }
配套注意事项:
- 微软官方托管的Azure DevOps Pipeline代理默认预装PowerShell 7+(即
pwsh),无需额外安装;如果使用自托管代理,需要手动安装PowerShell 7并将其加入系统PATH。 - 如果必须使用Windows自带的旧版Windows PowerShell(仅支持Windows代理),可将interpreter替换为
["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File"],注意文件名必须为全小写带.exe后缀。 - interpreter字段已经指定了脚本解释器,不需要在command字段中重复写
powershell/pwsh调用命令,否则会出现命令嵌套执行错误。 -ExecutionPolicy Bypass参数用于绕过PowerShell默认的执行策略限制,避免Pipeline环境下因为执行策略禁止运行脚本触发报错。
内容的提问来源于stack exchange,提问作者Muhammad_Bilal
相关产品推荐
相关产品推荐

