Azure CLI堡垒机SSH命令在PowerShell中正常运行但在Git Bash(VS Code)中报错
Azure CLI堡垒机SSH命令在PowerShell中正常运行但在Git Bash(VS Code)中报错
我最近碰到一个棘手的问题:用Azure CLI的堡垒机SSH命令连接Azure虚拟机时,在PowerShell里能顺利执行,但换到VS Code的Git Bash环境就报错,提示资源ID无效。
命令详情
原始的可执行命令(无换行):
az network bastion ssh --name hyphen-text --resource-group another-hypen-text --target-resource-id /subscriptions/1c715f48-0ae9-121a-44f2-72683c152f33/resourceGroups/text-with-hyphen/providers/Microsoft.Compute/virtualMachines/more-text-with-hyphen --auth-type AAD
为了可读性我加了换行转义符\,占位符替换后的版本:
az network bastion ssh \ --name <somename> \ --resource-group <some_rg> \ --target-resource-id /subscriptions/<sub_id>/resourceGroups/<some_rg>/providers/Microsoft.Compute/virtualMachines/<some_vm> \ --auth-type AAD
注:这些换行转义符\不影响Bash和PowerShell的执行,我也测试过无换行的版本,结果一致。
问题现象
- PowerShell中执行命令完全正常,能成功连接虚拟机
- Git Bash中执行时,弹出错误提示:
Please enter a valid resource ID. If this is not working, try opening the JSON view of your resource (in the Overview tab), and copying the full resource ID.
已尝试的排查操作
我试过把所有参数值用双引号括起来,但问题依然存在,而且两个环境使用的是同一个Azure CLI版本。
环境信息
- Bash版本:GNU bash, version 5.2.15(1)-release (x86_64-pc-msys)
- PowerShell版本:5.1.19041.3930
- Azure CLI版本:2.56.0
可能的解决方向
经过排查,这类问题通常和Git Bash的路径解析或字符转义有关,你可以尝试以下几种方法:
- 用单引号包裹资源ID参数:在Git Bash中,单引号会完全保留字符串的原始内容,避免转义问题,比如:
az network bastion ssh \ --name <somename> \ --resource-group <some_rg> \ --target-resource-id '/subscriptions/<sub_id>/resourceGroups/<some_rg>/providers/Microsoft.Compute/virtualMachines/<some_vm>' \ --auth-type AAD
- 检查资源ID中的特殊字符:虽然你的资源ID看起来是标准格式,但Git Bash可能对某些字符(比如连字符)的处理和PowerShell不同,建议直接从Azure门户复制完整的资源ID,确保没有隐藏的特殊字符或空格。
- 禁用Git Bash的路径转换:Git Bash默认会把Windows风格的路径转换为Unix风格,但这里的资源ID是Azure的格式,可能被误转换。可以设置环境变量
MSYS_NO_PATHCONV=1后再执行命令:
MSYS_NO_PATHCONV=1 az network bastion ssh --name <somename> --resource-group <some_rg> --target-resource-id /subscriptions/<sub_id>/resourceGroups/<some_rg>/providers/Microsoft.Compute/virtualMachines/<some_vm> --auth-type AAD
- 使用完整的Windows路径执行Azure CLI:有时候Git Bash调用CLI的方式有问题,你可以尝试用Azure CLI的完整路径执行,比如:
/c/Program\ Files/Microsoft\ SDKs/Azure/CLI2/wbin/az.cmd network bastion ssh ...
备注:内容来源于stack exchange,提问作者M.T
相关产品推荐
相关产品推荐

