如何在az vm run-command中使用ConfigurationName参数解决权限问题?
解决Azure VM Run-Command执行PowerShell脚本的双跳权限问题
问题背景
- 场景1:通过
PowerShellOnTargetMachines@3任务调用Invoke-Command并指定ConfigurationName,使用用户凭据执行VM本地的test.ps1脚本,连接SQL Server正常。 - 场景2:用
AzureCLI@2的az vm run-command invoke直接执行仓库中的test.ps1,触发错误:
原因是Run-Command默认以Invoke-Sqlcmd : Cannot open database \"DBname\" requested by the login. The login failed.\nLogin failed for user 'NT AUTHORITY\\SYSTEM'NT AUTHORITY\SYSTEM账户执行脚本,无法处理Kerberos双跳(从VM到SQL Server的身份传递),而场景1通过Invoke-Command的ConfigurationName参数解决了该问题。
核心限制
az vm run-command invoke本身不支持直接传递ConfigurationName参数,因为它默认以系统账户在VM内执行操作。要解决权限问题,需要在Run-Command执行的脚本内部,模拟场景1的用户会话逻辑。
解决方案:在Run-Command脚本中嵌套Invoke-Command
通过在az vm run-command的脚本内容中,用指定用户凭据调用Invoke-Command并传入ConfigurationName,让目标脚本以用户身份运行,支持双跳验证。
修改后的AzureCLI任务配置
- task: AzureCLI@2 displayName: 'testrun' inputs: azureSubscription: 'subname' scriptType: 'pscore' scriptLocation: 'inlineScript' inlineScript: | az vm run-command invoke --command-id RunPowerShellScript --name servername --resource-group RGname --scripts @" # 定义用户凭据 $Username = "username" $Password = ConvertTo-SecureString -String "password" -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential ($Username, $Password) # 以指定用户身份调用目标脚本,复用场景1的会话配置 Invoke-Command -ComputerName localhost -Credential `$cred -ConfigurationName configname -ScriptBlock { & D:\test.ps1 } "@
关键细节说明
- 脚本传递:如果仓库中的
test.ps1未预先部署到VM,可将脚本内容直接嵌入到--scripts参数中,或者先通过az vm run-command将脚本文件上传到VM本地路径。 - 会话配置验证:确保VM上的
configname会话配置已正确配置(如启用CredSSP或Kerberos约束委派),与场景1使用的配置一致。 - 转义处理:注意在inlineScript中对
$cred进行转义(\$cred`),避免AzureCLI解析时丢失变量。
替代方案:用Start-Process以用户身份执行
如果不需要依赖会话配置,也可以用Start-Process直接以用户身份启动PowerShell执行脚本:
$Username = "username" $Password = ConvertTo-SecureString -String "password" -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential ($Username, $Password) Start-Process powershell.exe -Credential $cred -ArgumentList "-File D:\test.ps1" -Wait -NoNewWindow
但该方式不支持ConfigurationName,仅适用于无需会话配置的场景。
内容的提问来源于stack exchange,提问作者Anusha Madhusudhanan
相关产品推荐
相关产品推荐

