Active Choice pipeline script

Hello community,

we try to build a form active choice with some api call to get data like “AWS account”…
We try to return an array but in the form the input is empty :

This is our code :

properties([
    parameters([
        [$class: 'ChoiceParameter', 
            choiceType: 'PT_SINGLE_SELECT',
            description: 'Select your Cloud account',
            filterLength: 1,
            filterable: true,
            name: 'cloudAccount',
            script: [$class: 'GroovyScript',
                fallbackScript: [
                    classpath: [],
                    script: 'return ["ERROR"]'
                ],
                script: [
                    classpath: [], 
                    script: 
                        '''   
                        try {
                        // Define the request headers
                        def headers = [
                            [maskValue: false, name: 'Authorization', value: 'Bearer My-Token],
                            [maskValue: false, name: 'ConsistencyLevel', value: 'eventual']
                        ]
                        
                        // Define the API request URL
                        def url = 'https://graph.microsoft.com/v1.0/users/me/memberOf/microsoft.graph.group?' +
                                '$count=true&$orderby=displayName&$filter=startswith(displayName,\'AWS\')&$select=displayName'
                        
                        // Perform the HTTP request
                        def response = httpRequest(
                            acceptType: 'APPLICATION_JSON', 
                            contentType: 'APPLICATION_JSON', 
                            customHeaders: headers,
                            httpProxy: 'usproxy.xx.xx.xx.xx',
                            proxyAuthentication: 'my-account-proxy',
                            ignoreSslErrors: true,
                            url: url
                        )
                        
                        // Debug: Print raw response
                        echo "Response: ${response}"
                        echo "Status: ${response.status}"
                        echo "Headers: ${response.headers}"
                        
                        // Parse JSON from the response content
                        def jsonResponse = readJSON text: response.content
                        
                        // Log the parsed JSON (optional)
                        echo "Parsed JSON response: ${jsonResponse}"
                        
                        // Check if there are any groups in the response
                        if (jsonResponse.value?.size() > 0) {
                            def acCloudAccountList = []
                            def cloudAccountList = jsonResponse.value.each { group ->
                            acCloudAccountList << "'$group.displayName'"  // Adding each item as a string with quotes
                            }
                            echo "List of cloud accounts: ${acCloudAccountList}"
                            "return [${acCloudAccountList}]"
                        } else {
                            echo "No groups found or empty response."
                            return "No groups found."
                        }
                    } catch (Exception e) {
                        echo "Error occurred: ${e.message}"
                        currentBuild.result = 'FAILURE'
                        return "Error occurred: ${e.message}"
                    }
                    '''
                ]
            ]
        ]

    ])
])

When we execute in the pipeline the array is correct :

[Pipeline] echo
List of cloud accounts: ['AWS-xxxxx-Admins', 'AWS-xxxxxx-Admins', 'AWS scnext xxxxxx nonprod']
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Run Terraform)

Sorry we are very newbie on Jenkins :slight_smile:

"return [${acCloudAccountList}]"
should probably be
return acCloudAccountList

Thx for your help… Already try like this :

[$class: 'ChoiceParameter', 
            choiceType: 'PT_SINGLE_SELECT',
            description: 'Select your Cloud account',
            filterLength: 1,
            filterable: true,
            name: 'cloudAccount',
            script: [$class: 'GroovyScript',
                fallbackScript: [
                    classpath: [],
                    script: 'return ["ERROR"]'
                ],
                script: [
                    classpath: [], 
                    script: 
                        '''   
                        try {
                        // Define the request headers
                        def headers = [
                            [maskValue: false, name: 'Authorization', value: 'Bearer My-Token],
                            [maskValue: false, name: 'ConsistencyLevel', value: 'eventual']
                        ]
                        
                        // Define the API request URL
                        def url = 'https://graph.microsoft.com/v1.0/users/me/memberOf/microsoft.graph.group?' +
                                '$count=true&$orderby=displayName&$filter=startswith(displayName,\'AWS\')&$select=displayName'
                        
                        // Perform the HTTP request
                        def response = httpRequest(
                            acceptType: 'APPLICATION_JSON', 
                            contentType: 'APPLICATION_JSON', 
                            customHeaders: headers,
                            httpProxy: 'usproxy.xx.xx.xxx.com',
                            proxyAuthentication: 'xxxx-xxxxx',
                            ignoreSslErrors: true,
                            url: url
                        )
                        
                        // Debug: Print raw response
                        echo "Response: ${response}"
                        echo "Status: ${response.status}"
                        echo "Headers: ${response.headers}"
                        
                        // Parse JSON from the response content
                        def jsonResponse = readJSON text: response.content
                        
                        // Log the parsed JSON (optional)
                        echo "Parsed JSON response: ${jsonResponse}"
                        
                        // Check if there are any groups in the response
                        if (jsonResponse.value?.size() > 0) {
                            def acCloudAccountList = []
                            def cloudAccountList = jsonResponse.value.each { group ->
                            acCloudAccountList << "'$group.displayName'"  // Adding each item as a string with quotes
                            }
                            echo "List of cloud accounts: ${acCloudAccountList}"
                            return acCloudAccountList
                        } else {
                            echo "No groups found or empty response."
                            return "No groups found."
                        }
                    } catch (Exception e) {
                        echo "Error occurred: ${e.message}"
                        currentBuild.result = 'FAILURE'
                        return "Error occurred: ${e.message}"
                    }
                    '''
                ]
            ]
        ],

But the array is also empty in the form :frowning:

You have this in the log output:

List of cloud accounts: ['AWS-xxxxx-Admins', 'AWS-xxxxxx-Admins', 'AWS scnext xxxxxx nonprod']

Is this coming from the script you defined in the active choice parameter?
The thing is that a script in an active choice parameter is not a pipeline script. Means you can’t use the steps you use in the Jenkinsfile. It must be plain groovy afaik. At the time the active choice script is executed the pipeline is not yet running

So you have to rewrite the script inside the active choice parameter without making use of any pipeline specific steps, e.g. httpRequest or readJSON are pipeline steps, there are no such functions in plain groovy. Also echo doesn’t work, maybe when you use println that would work and the output is shown in the Jenkins logs but it will never be visible in the job logs.

Do you have an example in groovy to call an external api with token, proxy + auth and how to parse a json? Or where we can find a documentation?

No. As this is standard groovy you should be able to help yourself with a good search engine (just consider that Jenkins is using groovy 2.4 so a bit older version)