[英]Powershell script in declarative jenkins pipeline
我正在使用環境憑據來獲取用戶名和密碼。 當我回應它們時,它們被完美地打印為****
。
接下來是powershell命令,當我單獨運行它們時,所有命令都可以完美運行。 但是通過 Jenkins 管道,它向我拋出以下錯誤:
groovy.lang.MissingPropertyException:沒有這樣的屬性:類的psw:groovy.lang.Binding
誰能解釋一下在 Jenkins 管道中合並 powershell 的正確方法嗎?
environment {
CREDENTIAL = credentials('Test')
}
stage('Deployment') {
steps {
echo "$CREDENTIAL_USR"
echo "$CREDENTIAL_PSW"
powershell """($psw = ConvertTo-SecureString -String $CREDENTIAL_PSW -AsPlainText -Force)"""
powershell """($mySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $CREDENTIAL_USR, $psw -Verbose)"""
powershell """(Set-Item WSMan:/localhost/Client/TrustedHosts -Value "*" -Force)"""
powershell """($session = New-PSSession -ComputerName "192.111.111.111" -Credential $mySecureCreds)"""
萬一有人在這里,並且仍在試圖找出問題所在。 我將分享對我有用的解決方案。
在多行字符串中的變量“$”符號之前使用轉義符。
powershell ("""
\$psw = ConvertTo-SecureString -String \$CREDENTIAL_PSW -AsPlainText -Force
\$mySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList \$CREDENTIAL_USR, \$psw -Verbose
Set-Item WSMan:/localhost/Client/TrustedHosts -Value "*" -Force
\$session = New-PSSession -ComputerName "192.111.111.111" -Credential \$mySecureCreds
""")
目前,您正在自己的 powershell 進程中運行每一行,因此前一行的結果對下一個命令不可用。
我認為您只需要將腳本移動到多行字符串中即可:
powershell ("""
$psw = ConvertTo-SecureString -String $CREDENTIAL_PSW -AsPlainText -Force
$mySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $CREDENTIAL_USR, $psw -Verbose
Set-Item WSMan:/localhost/Client/TrustedHosts -Value "*" -Force
$session = New-PSSession -ComputerName "192.111.111.111" -Credential $mySecureCreds
""")
您可以像這樣在 jenkins 管道中輕松運行多行 powershell 命令。 例如,如果您想使用服務主體登錄 azure,您將執行如下操作:
powershell '''
$pass = ConvertTo-SecureString your_client_secret -AsPlainText –Force
$cred = New-Object -TypeName pscredential –ArgumentList your_client_id, $pass
Login-AzureRmAccount -Credential $cred -ServicePrincipal –TenantId your_tenant_id
-vaultName "eusdevmbe2keyvault" -name "normalizedcontainername").SecretValueText
'''
在此處查看參考https://jenkins.io/blog/2017/07/26/powershell-pipeline/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.