Jenkins -> powershell Invoke-WebRequest with UseDefaultCredentials

时间:2021-03-19 14:00:24

标签: powershell jenkins

我尝试在 Jenkins 从站上执行 PowerShell 脚本。它看起来像:

stage ("Get") {
    steps {
        powershell( 
            script: '''
                $srcCommonParams = @{
                    Method = 'GET'
                    Uri = $getUri
                }
                Invoke-WebRequest @srcCommonParams -UseDefaultCredentials -Verbose

问题是默认凭证从何而来?我认为它们是代表我的 Jenkins slave Windows 服务运行的那些。问题是我的 Jenkins slave 以用户 A 身份运行,但 Invoke-WebRequest 抱怨用户 B 没有足够的权限来执行请求。

1 个答案:

答案 0 :(得分:2)

您必须从 Jenkins 获得凭据。 您必须添加 'withCredentials' 并在与此类似的 powershell 中添加:

stage ("Get") {
steps {  withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'your-credentials-id',usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']])

powershell( 
    script: '''
          $encryptedPassword = ConvertTo-SecureString "%PASSWORD%" -AsPlainText -Force
          $mycreds = New-Object System.Management.Automation.PSCredential ("%USERNAME%", $encryptedPassword)
          $srcCommonParams = @{
            Method = 'GET'
            Uri = $getUri
        }
Invoke-WebRequest @srcCommonParams -Credential $mycreds -Verbose
相关问题