解决Azure DevOps构建问题:脚本签名详解
·
引言
在使用Azure DevOps进行持续集成和持续交付(CI/CD)时,常常会遇到一些与PowerShell脚本执行策略相关的错误。本文将通过一个真实案例,详细讲解如何通过创建自签名证书并签署脚本来解决Azure DevOps构建过程中遇到的脚本签名问题。
背景
假设你有三台运行Azure DevOps Self-hosted agent的机器,版本为3.236.1。你在进行构建时,遇到了以下错误:
File C:\agent\agent01\_work\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.231.0\ps_modules\VstsTaskSdk\VstsTaskSdk.psm1 cannot be loaded. The file ... is not digitally signed. You cannot run this script on the current system.
尝试更改执行策略(Execution Policy)后,发现仅当设置为Machine Policy时,构建才能成功,但由于组织的组策略限制,无法长期维持此设置。
解决方案
解决此问题的方法之一是通过签署所有相关的PowerShell脚本文件来确保它们可以安全执行。以下是详细的步骤:
第一步:创建自签名证书
在PowerShell(管理员模式)中执行以下命令:
$authenticode = New-SelfSignedCertificate -Subject "AZUR-SelfhostedAgent" -CertStoreLocation Cert:\LocalMachine\My -Type CodeSigningCert
第二步:将证书复制到根证书存储和受信任的发布者存储
$rootStore = [System.Security.Cryptography.X509Certificates.X509Store]::new("Root","LocalMachine")
$rootStore.Open("ReadWrite")
$rootStore.Add($authenticode)
$rootStore.Close()
$publisherStore = [System.Security.Cryptography.X509Certificates.X509Store]::new("TrustedPublisher","LocalMachine")
$publisherStore.Open("ReadWrite")
$publisherStore.Add($authenticode)
$publisherStore.Close()
第三步:验证证书存储
确认证书是否正确添加到相应的存储中:
Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Subject -eq "CN=AZUR-SelfhostedAgent"}
Get-ChildItem Cert:\LocalMachine\Root | Where-Object {$_.Subject -eq "CN=AZUR-SelfhostedAgent"}
Get-ChildItem Cert:\LocalMachine\TrustedPublisher | Where-Object {$_.Subject -eq "CN=AZUR-SelfhostedAgent"}
第四步:签署脚本文件
使用创建的证书签署所有相关的.psm1和.ps1文件:
$codeCertificate = Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Subject -eq "CN=AZUR-SelfhostedAgent"}
Set-AuthenticodeSignature -FilePath "C:\agent\agent01\_work\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.231.0\ps_modules\VstsTaskSdk\*.ps*" -Certificate $codeCertificate
Set-AuthenticodeSignature -FilePath "C:\agent\agent01\_work\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.231.0\*.ps1" -Certificate $codeCertificate
实例与结果
在执行上述步骤后,Azure DevOps的构建任务能够顺利完成。然而,用户在构建验证步骤中遇到临时生成的未签名脚本文件的问题。这可以通过在构建过程中动态签署这些临时文件来解决,尽管这可能需要进一步的脚本或任务配置。
结论
通过创建并应用自签名证书,可以有效解决Azure DevOps构建过程中由于PowerShell脚本未签名导致的错误问题。这种方法不仅解决了即时问题,还提供了一种在组织安全策略下持续工作的解决方案。
后记
如果在执行上述步骤后仍然遇到问题,建议详细检查构建定义和脚本执行环境,确保所有依赖项和配置都已正确设置。必要时,可以寻求Azure DevOps社区或专业支持的帮助。
更多推荐


所有评论(0)