如何通过Azure Automation在Ubuntu镜像Azure VM执行bash脚本及New-SshSession问题
一、能否在Azure Automation Runbook中调用Bash脚本?
当然可以!有几种可靠的方式实现,不用纠结于直接调用本地bash脚本文件,而是可以通过Runbook间接执行bash命令或脚本内容:
- 使用Azure原生的
Invoke-AzVMRunCommand(最推荐)
这是Azure官方提供的在VM上执行脚本的方式,不需要建立SSH会话,直接通过Azure API触发,完美支持Linux VM的bash脚本和Windows VM的PowerShell脚本。你可以把bash命令直接写在Runbook里,或者引用存储在Azure存储账户里的脚本文件。
示例PowerShell Runbook代码:
# 导入Az.Compute模块(Azure Automation默认已包含,确保已启用) Import-Module Az.Compute $vmParams = @{ ResourceGroupName = "your-resource-group-name" VMName = "your-ubuntu-vm-name" CommandId = "RunShellScript" # 针对Linux的固定CommandId ScriptString = @" #!/bin/bash # 这里写你的安装命令,比如: apt update && apt install -y nginx systemctl enable --now nginx "@ } Invoke-AzVMRunCommand @vmParams
- 通过PowerShell Runbook建立SSH会话执行bash
如果你坚持用SSH,也可以实现,但需要解决你遇到的模块兼容性问题,后面会详细说明。
二、New-SshSession报错的原因及前提条件
你遇到的Unable to create SSH client object: Exception calling ".ctor" with "4" argument(s): "Could not load type 'System.Security.Cryptography.HMACRIPEMD160'..."错误,根源是Azure Automation的PowerShell运行环境(基于.NET Framework)不包含HMACRIPEMD160算法——这个算法在较新的.NET版本中被标记为过时或移除,而Posh-SSH模块的底层依赖了它。
关于New-SshSession的正确前提条件:
- Linux VM端:
- 开启SSH服务(Ubuntu默认已启用,可通过
systemctl status ssh确认) - 网络安全组(NSG)允许Azure Automation服务的IP段访问VM的22端口(也可以直接允许你的Automation账户的出站IP,可在Automation账户的“网络设置”中查看)
- 确保SSH用户有足够权限执行安装命令(比如配置免密sudo,或在命令中包含sudo)
- 开启SSH服务(Ubuntu默认已启用,可通过
- Azure Automation端:
- 必须将
Posh-SSH模块导入到你的Automation账户(默认不包含):需要从PowerShell Gallery下载Posh-SSH模块,上传到Automation账户的“模块”库中,等待导入完成
- 必须将
但即使完成以上配置,你依然会遇到算法缺失的问题,所以这个方式并不推荐。
替代方案:避开Posh-SSH,用更兼容的方式
如果一定要用SSH,你可以尝试在PowerShell Runbook中直接调用原生的ssh命令(Automation Worker环境支持该命令),示例:
# 从Automation凭据资产中读取SSH密钥和用户名 $sshCred = Get-AutomationPSCredential -Name "YourSSHCredential" $privateKeyPath = "C:\temp\id_rsa" $sshCred.GetNetworkCredential().Password | Out-File $privateKeyPath -Encoding ASCII chmod 600 $privateKeyPath $sshCommand = @" ssh -i $privateKeyPath $($sshCred.UserName)@your-vm-ip "sudo apt update && sudo apt install -y nginx" "@ Invoke-Expression $sshCommand
不过这种方式需要在Automation账户中配置SSH密钥凭据,步骤相对繁琐。
还是回到最推荐的Invoke-AzVMRunCommand,它不需要处理SSH密钥、端口开放(只要Azure API能访问VM即可,默认VM允许Azure服务访问),而且更稳定可靠。
另外,完全不需要在Linux机器上安装.NET库——问题出在Azure Automation的PowerShell运行环境,和Linux端无关。
内容的提问来源于stack exchange,提问作者roccmol09

