声明性jenkins管道中的Powershell脚本

时间:2018-05-31 10:53:45

标签: powershell jenkins jenkins-plugins

我正在使用环境凭据来获取用户名和密码。当我回应它们时,它们被完美地打印为****

接下来是powershell命令,当我单独运行它们时,所有命令都能正常工作。但是通过Jenkins管道,它抛出了以下错误:

  

groovy.lang.MissingPropertyException:没有这样的属性: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)"""

3 个答案:

答案 0 :(得分: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
""")

答案 1 :(得分:1)

万一有人在这里,并且仍然试图找出问题所在。我将分享对我有用的解决方案。

在多行字符串中的变量“ $”之前使用转义。

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 :(得分:0)

您可以像这样在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”-名称“ normalizedcontainername”)。SecretValueText                '''

在此处查看参考文献https://jenkins.io/blog/2017/07/26/powershell-pipeline/