如何为Jenkins Pipeline动态设置选择参数
Dynamic Choice Parameters from API in Jenkins Pipeline
I’ve adjusted your pipeline to dynamically pull .zip artifact filenames from an API and use them as choices in the input prompt—here’s the modified code and a breakdown of how it works:
pipeline { agent any stages { stage("Fetch Artifacts & Prompt Release") { steps { script { // 1. Call your API to get the artifact list (replace with your actual endpoint) def apiResponse = sh( script: 'curl -s "https://your-api-endpoint/artifacts"', returnStdout: true ).trim() // 2. Parse the response to extract only .zip filenames // Adjust this parsing logic to match your API's output format def artifactList = new groovy.json.JsonSlurper().parseText(apiResponse) def zipArtifacts = artifactList.findAll { it.endsWith('.zip') }.join('\n') // Fallback if no .zip artifacts are found (prevents input prompt failure) if (zipArtifacts.isEmpty()) { zipArtifacts = 'no-zip-artifacts-found' echo "Warning: No .zip artifacts returned from the API" } // 3. Prompt user with dynamically generated choices env.RELEASE_SCOPE = input( message: 'Select the .zip artifact to release:', ok: 'Proceed with Release!', parameters: [ choice( name: 'RELEASE_SCOPE', choices: zipArtifacts, description: 'Choose which artifact to deploy' ) ] ) } echo "Selected artifact for release: ${env.RELEASE_SCOPE}" } } } }
Key Details to Note:
- API Call: The example uses
curlto fetch the API response. If your Jenkins agent doesn’t havecurlinstalled, or if you need to handle authentication/headers, use Jenkins’ HTTP Request Plugin for a native, configurablehttpRequeststep instead. - Response Parsing: This code assumes your API returns a JSON array of filenames. If your API returns plain text (one filename per line), skip the JSON parsing and directly filter lines ending with
.zip. - Edge Case Handling: Added a fallback option to prevent the input prompt from failing if no .zip artifacts are returned—you can adjust this to abort the pipeline instead if that fits your workflow.
- Dynamic Choices: The
choicesparameter expects a newline-separated string, so we usejoin('\n')to convert our list of filenames into the required format.
内容的提问来源于stack exchange,提问作者Springhills
相关产品推荐
相关产品推荐

