我正在尝试在 Azure DevOps 管道中运行 Powershell 脚本。 由于脚本使用
Az
模块命令,我们决定在管道中使用 AzurePowerShell@5
任务。
默认情况下,Azure PowerShell v5 使用 PowerShell Core for Linux 代理
由于我们有自托管的Linux代理,因此在使用AzurePowerShell@5
之前,需要在代理上手动安装
PowerShell Core和Az模块。
按照这些步骤安装powershell核心,并按照此处提到的步骤安装
Az
模块。
# Install powershell core
sudo apt-get update
sudo apt-get install -y wget apt-transport-https software-properties-common
wget -q "https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/packages-microsoft-prod.deb"
sudo dpkg -i packages-microsoft-prod.deb
sudo apt-get update
sudo apt-get install -y powershell
# Install Az Module
Install-Module -Name Az -Repository PSGallery -RequiredVersion '11.1.0' -Force
Update-Module -Name Az -Force
但是当我们使用管道中的任务时,
- task: AzurePowerShell@5
name: test_script
displayName: 'test_script'
inputs:
azureSubscription: $(arm_service_connection)
ScriptType: 'FilePath'
ScriptPath: $(System.DefaultWorkingDirectory)/powershell_scripts/test_script.ps1
ScriptArguments: >
-subscriptionId $(subscription_id)
azurePowerShellVersion: 'OtherVersion'
preferredAzurePowerShellVersion: '11.1.0'
FailOnStandardError: true
pwsh: true
它给出了一个错误:
Generating script.
/usr/bin/pwsh -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command . '/agent/_work/_temp/f3210d6a-92eb-4665-92bd-9c6790840726.ps1'
File saved!
Exception: /agent/_work/_tasks/AzurePowerShell_72a1931b-effb-4d2e-8fd8-f8472a07cb62/5.231.0/Utility.ps1:94
Line |
94 | … throw ("Could not find the module path with given version …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Could not find the module path with given version.
##[error]PowerShell exited with code '1'.
##[error]PowerShell wrote one or more lines to the standard error stream.
如何解决这个问题?
我发现了一个博客这里解释了同样的事情。我还检查了错误中提到的file。
很明显,
AzurePowerShell@5
任务正在路径Az
寻找/usr/share/az_<azurePowerShellVersion>
模块文件。
因此,我使用以下脚本将模块安装在正确的路径中,并且它有效:
# Install powershell core
sudo apt-get update
sudo apt-get install -y wget apt-transport-https software-properties-common
wget -q "https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/packages-microsoft-prod.deb"
sudo dpkg -i packages-microsoft-prod.deb
sudo apt-get update
sudo apt-get install -y powershell
# Install Az Module in correct path
sudo mkdir -p /usr/share/az_11.1.0
sudo /usr/bin/pwsh -Command 'Find-Module -Name Az -RequiredVersion '11.1.0' -Repository 'PSGallery' | Save-Module -Path '/usr/share/az_11.1.0' -Force -Verbose'
确保 ado 代理用户对该模块目录和文件具有
read
和 execute
权限。
为任务指定这些参数对于选择正确的版本非常重要:
azurePowerShellVersion: 'OtherVersion'
preferredAzurePowerShellVersion: '11.1.0'