声明式Jenkins流水线中的PowerShell脚本

5
我正在使用环境凭据获取用户名和密码。当我输出它们时,它们被打印为****
接下来是PowerShell命令,当我单独运行它们时,所有命令都可以正常工作。但是通过Jenkins管道运行时,会抛出以下错误:

groovy.lang.MissingPropertyException: No such property: psw for class: 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)"""

2
有点晚了,但你最终找到了这个问题的答案吗? - fhuseynli
3个回答

6

如果有人还在尝试弄清楚问题,我将分享对我有效的解决方案。

在多行字符串中,在变量"$"符号之前使用转义。

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
""")

2
您可以像这样在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
           '''

请参考此处了解更多关于PowerShell管道的信息。


1

目前你正在每个行命令中单独运行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
""")

我尝试了你建议的使用多行字符串的方法,James。但是即使这样,我仍然得到相同的错误。 - Spidy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接