为Jenkins中的API PUT向PowerShell脚本添加参数

4urapxun  于 2022-11-02  发布在  Jenkins
关注(0)|答案(1)|浏览(178)

我遇到了一个问题,我想用参数“BuildVersion”替换正文中下面的文本“Test to Output”。API POST在硬编码时可以工作,但我想让它写回运行时捕获的AUT的exe,并添加到currentBuild。description,但就是搞不懂语法。有人能给我指出正确的方向吗?这是一个Jenkins脚本与PowerShell用于POST请求。

def BuildVersion = currentBuild.description
echo BuildVersion

powershell '''
    $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
    $headers.Add("Content-Type", "application/json")
    $headers.Add("Authorization", "token")

    $body = "{`n    `"value`": `"Test to Output`"`n}"

    $response = Invoke-RestMethod 'https://api.clickup.com/api/v2/task/task_id/field/field_id' -Method 'POST' -Headers $headers -Body $body
    $response | ConvertTo-Json
'''
}
ao218c7q

ao218c7q1#

使用withEnv将Groovy变量作为环境变量传递到PowerShell中。这比使用字符串插值法更安全,因为字符串插值法容易受到脚本注入的影响。
使用powershell returnStdout: true以字符串形式获取PowerShell的输出,然后使用JsonSlurper将其解析回对象。
我不知道REST API中JSON的格式,所以我写了???来代替您必须使用的JSON路径。

import groovy.json.JsonSlurper

def BuildVersion = currentBuild.description
echo BuildVersion

def responseJson = ''

withEnv(["BuildVersion=$BuildVersion"]) { 

    responseJson = powershell returnStdout: true, script: ''' 
        $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
        $headers.Add("Content-Type", "application/json")
        $headers.Add("Authorization", "token")

        $body = @{ value = $env:BuildVersion } | ConvertTo-Json

        $response = Invoke-RestMethod 'https://api.clickup.com/api/v2/task/task_id/field/field_id' -Method 'POST' -Headers $headers -Body $body
        $response | ConvertTo-Json
    '''
}

def responseData = new JsonSlurper().parseText( responseJson )

// TODO: Replace ??? by the JSON path
currentBuild.description = responseData.???

相关问题