Home > Software design >  Add a parameter to PowerShell script for API PUT in Jenkins
Add a parameter to PowerShell script for API PUT in Jenkins

Time:09-22

I am having an issue where I want to replace the text below in the body, 'Test to Output', with a parameter 'BuildVersion'. The API POST works when hardcoded but I want it to write back the exe for the AUT which is captured at runtime, and added to currentBuild.description, but just can't figure out the syntax. Can anyone point me in the right direction please? It is a Jenkins script with PowerShell used for the POST request.

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
'''
}

CodePudding user response:

Use withEnv to pass Groovy variables into PowerShell as environment variables. This is safer than using string interpolation, which is susceptible to script injection.

Use powershell returnStdout: true to get output of PowerShell as a string, then parse it back into objects using JsonSlurper.

I don't know format of the JSON from REST API, so I wrote ??? in place of the JSON path you have to use.

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.???
  • Related