带有 WithCredentials 和 Powershell 的声明式 Jenkins

Spi*_*idy 5 jenkins jenkins-plugins jenkins-pipeline

stage('Deployment') {
steps {
    withCredentials([string(credentialsId: 'Test', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
        powershell '$pass = ConvertTo-SecureString -AsPlainText "${PASSWORD}" -Force'
        powershell '$SecureString = "${pass}"'
        powershell '$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "${USERNAME}","${SecureString}"'
        powershell 'New-PSSession -ComputerName 192.123.123.123 -Credential "${MySecureCreds}"'
     }
     powershell 'Copy-Item "${ARTIFACT_PATH}" -Destination "${DESTINATION_PATH}" -ToSession -Recurse -Force'
     powershell 'Start-Process "iisreset.exe" -NoNewWindow -Wait'
     powershell 'Remove-Website -Name WebCareRecord'
     powershell 'Remove-WebAppPool WebCareRecord'
     powershell 'Get-WebBinding -Port 85 -Name WebCareRecord | Remove-WebBinding'
     powershell 'Start-Process "iisreset.exe" -NoNewWindow -Wait'
     powershell 'New-WebAppPool -Name WebCareRecord'
     powershell 'Set-ItemProperty "${POOL_PATH}" managedPipelineMode 0'
     powershell 'Set-ItemProperty "${POOL_PATH}" managedRuntimeVersion ""'
     powershell 'New-WebSite -Name WebCareRecord -Port 85 -PhysicalPath "${PHYSICAL_PATH}" -ApplicationPool WebCareRecord'
     powershell 'Start-Process "iisreset.exe" -NoNewWindow -Wait'
 }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试获取 Jenkins 凭据 ID、保护它并使用相同的凭据登录远程服务器。登录远程服务器后,将 jenkins 服务器中的工件复制到远程服务器。为此我收到错误

org.jenkinsci.plugins.credentialsbinding.impl.CredentialNotFoundException:凭证“Test”的类型为“带密码的用户名”,其中预期为“org.jenkinsci.plugins.plaincredentials.StringCredentials”。

Aur*_* N. 3

可能存在多个问题,我现在正在经历类似的过程,并且在 groovy 中的 powershell 中正确获取它感到很痛苦,所以这是我到目前为止注意到的:

您在一个 powershell 步骤中创建一个$pass变量,然后尝试在另一个 powershell 步骤中访问它,我认为它不会以这种方式工作,因为另一个步骤可能会在不同的 powershell 会话中启动,并且该 powershell 变量不再存在。

我会尝试这样的事情:

stage('Deployment') {
  steps {
    withCredentials([string(credentialsId: 'Test', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
        powershell """
          \$pass = ConvertTo-SecureString -AsPlainText $PASSWORD -Force
          \$SecureString = \$pass
        """
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

首先,使用多行语法""",以便不同的 powershell 语句位于同一会话中,并且这些变量可跨 powershell 命令使用。

其次,您转义了 powershell 变量\$pass\$SecureString,因此 groovy 不会尝试扩展它们,并且您不会在实际引用 groovy 变量(例如 )的地方转义变量$PASSWORD。请注意,$PASSWORD不必用引号引起来,因为 powershell 参数可以接受不带引号的字符串,但如果在方法中使用它,则应将其放入引号中SomePowershellMethod("$GROOVYVAR")

一般来说,我建议在故障排除时回显每个变量,看看您是否得到了您所期望的结果。