Jenkins pipeline - How to give choice parameters dynamically

﹥>﹥吖頭↗ 提交于 2020-05-12 04:44:37

问题


pipeline {
  agent any
  stages {
    stage("foo") {
        steps {
            script {
                env.RELEASE_SCOPE = input message: 'User input required', ok: 'Release!',
                        parameters: [choice(name: 'RELEASE_SCOPE', choices: 'patch\nminor\nmajor', 
                                     description: 'What is the release scope?')]
            }
            echo "${env.RELEASE_SCOPE}"
        }
    }
  }
}

In this above code, The choice are hardcoded (patch\nminor\nmajor) -- My requirement is to dynamically give choice values in the dropdown. I get the values from calling api - Artifacts list (.zip) file names from artifactory In the above example, It request input when we do the build, But i want to do a "Build with parameters"

Please suggest/help on this.


回答1:


Depends how you get data from API there will be different options for it, for example let's imagine that you get data as a List of Strings (let's call it releaseScope), in that case your code be following:

...
script {
    def releaseScopeChoices = ''
    releaseScope.each {
        releaseScopeChoices += it + '\n'
    }

    parameters: [choice(name: 'RELEASE_SCOPE', choices: ${releaseScopeChoices}, description: 'What is the release scope?')]
}
...


hope it will help.




回答2:


This is a cutdown version of what we use. We separate stuff into shared libraries but I have consolidated a bit to make it easier.

Jenkinsfile looks something like this:

#!groovy
@Library('shared') _
def imageList = pipelineChoices.artifactoryArtifactSearchList(repoName, env.BRANCH_NAME)
imageList.add(0, 'build')
properties([
    buildDiscarder(logRotator(numToKeepStr: '20')),
    parameters([
        choice(name: 'ARTIFACT_NAME', choices: body.artifacts.join('\n'), description: '')
    ])
])

Shared library that looks at artifactory, its pretty simple. Essentially make GET Request (And provide auth creds on it) then filter/split result to whittle down to desired values and return list to Jenkinsfile.

import com.cloudbees.groovy.cps.NonCPS
import groovy.json.JsonSlurper
import java.util.regex.Pattern
import java.util.regex.Matcher   

List artifactoryArtifactSearchList(String repoKey, String artifact_name, String artifact_archive, String branchName) {
    // URL components
    String baseUrl = "https://org.jfrog.io/org/api/search/artifact"
    String url = baseUrl + "?name=${artifact_name}&repos=${repoKey}"

    Object responseJson = getRequest(url)

    String regexPattern = "(.+)${artifact_name}-(\\d+).(\\d+).(\\d+).${artifact_archive}\$"

    Pattern regex = ~ regexPattern
    List<String> outlist = responseJson.results.findAll({ it['uri'].matches(regex) })
    List<String> artifactlist=[]

    for (i in outlist) {
        artifactlist.add(i['uri'].tokenize('/')[-1])
    }

    return artifactlist.reverse()
}

// Artifactory Get Request - Consume in other methods
Object getRequest(url_string){

    URL url = url_string.toURL()

    // Open connection
    URLConnection connection = url.openConnection()

    connection.setRequestProperty ("Authorization", basicAuthString())

    // Open input stream
    InputStream inputStream = connection.getInputStream()
    @NonCPS
    json_data = new groovy.json.JsonSlurper().parseText(inputStream.text)
    // Close the stream
    inputStream.close()

    return json_data
}

// Artifactory Get Request - Consume in other methods
Object basicAuthString() {
    // Retrieve password
    String username = "artifactoryMachineUsername"
    String credid = "artifactoryApiKey"
    @NonCPS
    credentials_store = jenkins.model.Jenkins.instance.getExtensionList(
        'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
        )
    credentials_store[0].credentials.each { it ->
        if (it instanceof org.jenkinsci.plugins.plaincredentials.StringCredentials) {
            if (it.getId() == credid) {
                apiKey = it.getSecret()
            }
        }
    }
    // Create authorization header format using Base64 encoding
    String userpass = username + ":" + apiKey;
    String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

    return basicAuth

}



回答3:


The example of Jenkinsfile below contains AWS CLI command to get the list of Docker images from AWS ECR dynamically, but it can be replaced with your own command. Active Choices Plug-in is required.

Note! You need to approve the script specified in parameters after first run in "Manage Jenkins" -> "In-process Script Approval", or open job configuration and save it to approve automatically (might require administrator permissions).

properties([
  parameters([[
    $class: 'ChoiceParameter',
    choiceType: 'PT_SINGLE_SELECT',
    description: '',
    filterLength: 1,
    filterable: false,
    name: 'image',
    script: [
      $class: 'GroovyScript',
      fallbackScript: [classpath: [], sandbox: false, script: 'return ["none"]'],
      script: [
        classpath: [],
        sandbox: false,
        script: '''\
          def repository = "frontend"
          def aws_ecr_cmd = "aws ecr list-images" +
                            " --repository-name ${repository}" +
                            " --filter tagStatus=TAGGED" +
                            " --query imageIds[*].[imageTag]" +
                            " --region us-east-1 --output text"
          def aws_ecr_out = aws_ecr_cmd.execute() | "sort -V".execute()
          def images = aws_ecr_out.text.tokenize().reverse()
          return images
        '''.stripIndent()
      ]
    ]
  ]])
])

pipeline {
  agent any

  stages {  
    stage('First stage') {
      steps {
        sh 'echo "${image}"'
      }
    }
  }
}



回答4:


choiceArray = [ "patch" , "minor" , "major" ]

properties([
    parameters([
            choice(choices: choiceArray.collect { "$it\n" }.join(' ') ,
                    description: '',
                    name: 'SOME_CHOICE')

    ])
])


来源:https://stackoverflow.com/questions/49525677/jenkins-pipeline-how-to-give-choice-parameters-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!