Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[JENKINS-34617] Add a @Symbol for "extendedChoice" #25

Merged
merged 1 commit into from
Apr 1, 2019
Merged

[JENKINS-34617] Add a @Symbol for "extendedChoice" #25

merged 1 commit into from
Apr 1, 2019

Conversation

rodrigc
Copy link
Contributor

@rodrigc rodrigc commented Mar 4, 2019

This allows extendedChoice() to be used in the parameters
block of a declarative pipeline.

For example:

parameters {
    extendedChoice( 
        defaultValue: 'One,Two,Three,Four', 
        description: '', 
        multiSelectDelimiter: ',', 
        name: 'SAMPLE_EXTENDED_CHOICE', 
        quoteValue: false, 
        saveJSONParameterToFile: false, 
        type: 'PT_CHECKBOX', 
        value:'One,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten', 
        visibleItemCount: 10)
    }

This allows extendedChoice() to be used in the parameters
block of a declarative pipeline.
@agray
Copy link
Member

agray commented Mar 4, 2019

Can the value attribute be "calculated" as the result of a groovy script? :)

From a shared library?

@rodrigc
Copy link
Contributor Author

rodrigc commented Mar 4, 2019

@agray I don't know. I just tried this patch and used extendedChoice() in one of my pipelines

@agray
Copy link
Member

agray commented Mar 4, 2019

@rodrigc would be a great feature to add that has been missing from declarative pipelines (AFAIK).

Happy for someone to tell me if such functionality exists elsewhere to extend this lack of functionality in choice() parameter.

@zentavr
Copy link

zentavr commented Mar 20, 2019

I wonder when this functionality will be available for the wide public?

@rodrigc
Copy link
Contributor Author

rodrigc commented Mar 20, 2019

@zentavr I emailed the plugin maintainer about this plugin. He did not respond yet

@zentavr
Copy link

zentavr commented Mar 20, 2019

@oleg-nenashev I wonder how the PR gets accepted in this organization?
We do really need this feature in the wide public!

@oleg-nenashev
Copy link
Member

@zentavr PRs are being accepted and released by the plugin maintainers. If there is no active plugin maintainers, there is an adoption process: https://wiki.jenkins.io/display/JENKINS/Adopt+a+Plugin .

If anyone is interested to get this fix out of the door, please feel free to request ownership of the plugin.

@zentavr
Copy link

zentavr commented Mar 21, 2019

I forked this repo and did a build with this patch here. Testing that locally now.

@zentavr
Copy link

zentavr commented Mar 21, 2019

Works like a charm! :)

        extendedChoice(
            name: 'lambda_api_key',
            description: 'Artifact for api_key AWS Lambda',
            multiSelectDelimiter: ',',
            visibleItemCount: 10,
            quoteValue: false,
            type: 'PT_SINGLE_SELECT',
            /* Default Property Value Settings */
            defaultPropertyFile: "${lambdasArtifactsListFile}",
            defaultPropertyKey: 'API_KEY_LATEST',
            /* Values List Settings */
            propertyFile: "${lambdasArtifactsListFile}",
            propertyKey: "API_KEY_LIST"
            )

Знімок екрана  о 16 31 55

@afrancoc2000
Copy link

I've been waiting for this for a while hope it gets merged soon, I will use the patch for now Thanks!!!

@dilipdesing
Copy link

When I tried to use the above code, I have got the following error,

java.lang.NoSuchMethodError: No such DSL method 'extendedChoice' found among steps [ansiColor, ansiblePlaybook, ansibleVault, archive, bat, build, catchError, checkout, deleteDir, dir, dockerFingerprintFrom, dockerFingerprintRun, dockerNode, echo, emailext, emailextrecipients, envVarsForTool, error, fileExists, getContext, git, input, isUnix, jiraComment, jiraIssueSelector, jiraSearch, junit, library, libraryResource, load, lock, mail, milestone, node, parallel, powershell, properties, publishHTML, pwd, readFile, readTrusted, resolveScm, retry, script, sh, slackSend, sleep, sshagent, stage, stash, step, svn, timeout, timestamps, tm, tool, unarchive, unstash, validateDeclarativePipeline, waitUntil, withContext, withCredentials, withDockerContainer, withDockerRegistry, withDockerServer, withEnv, wrap, writeFile, ws] or symbols [all, allOf, always, ant, antFromApache, antOutcome, antTarget, any, anyOf, apiToken, architecture, archiveArtifacts, artifactManager, attach, authorizationMatrix, batchFile, bitbucket, booleanParam, branch, brokenBuildSuspects, brokenTestsSuspects, buildButton, buildDiscarder, buildingTag, caseInsensitive, caseSensitive, certificate, changeRequest, changelog, changeset, checkoutToSubdirectory, choice, choiceParam, cleanWs, clock, cloud, command, credentials, cron, crumb, culprits, defaultView, demand, developers, disableConcurrentBuilds, disableResume, docker, dockerCert, dockerfile, downloadSettings, downstream, dumb, durabilityHint, envVars, environment, equals, expression, file, fileParam, filePath, fingerprint, frameOptions, freeStyle, freeStyleJob, fromScm, fromSource, git, github, githubPush, gradle, headRegexFilter, headWildcardFilter, hyperlink, hyperlinkToModels, inheriting, inheritingGlobal, installSource, isRestartedRun, jdk, jdkInstaller, jgit, jgitapache, jnlp, jobName, label, lastDuration, lastFailure, lastGrantedAuthorities, lastStable, lastSuccess, legacy, legacySCM, list, local, location, logRotator, loggedInUsersCanDoAnything, masterBuild, maven, maven3Mojos, mavenErrors, mavenMojos, mavenWarnings, modernSCM, myView, newContainerPerStage, node, nodeProperties, nonInheriting, nonStoredPasswordParam, none, not, overrideIndexTriggers, paneStatus, parallelsAlwaysFailFast, parameters, password, pattern, permanent, pipeline-model, pipelineTriggers, plainText, plugin, pollSCM, preserveStashes, projectNamingStrategy, proxy, queueItemAuthenticator, quietPeriod, rateLimitBuilds, recipients, remotingCLI, requestor, run, runParam, schedule, scmRetryCount, scriptApprovalLink, search, security, shell, skipDefaultCheckout, skipStagesAfterUnstable, slackNotifier, slave, sourceRegexFilter, sourceWildcardFilter, ssh, sshUserPrivateKey, stackTrace, standard, status, string, stringParam, swapSpace, tag, text, textParam, tmpSpace, toolLocation, triggeredBy, unsecured, upstream, upstreamDevelopers, usernameColonPassword, usernamePassword, viewsTabBar, weather, withAnt, zfs, zip] or globals [currentBuild, docker, env, params, pipeline, scm]

Looks like Jenkins doesnt support this function yet.?

@zentavr
Copy link

zentavr commented Mar 29, 2019

@dilipdesing - you can try the compiled version. Use my link above.

@rodrigc
Copy link
Contributor Author

rodrigc commented Mar 30, 2019

@zentavr I'm going to try to obtain write permissions to this plugin: jenkins-infra/repository-permissions-updater#1081

@vimil vimil merged commit c795ff0 into jenkinsci:master Apr 1, 2019
@zentavr
Copy link

zentavr commented Apr 1, 2019

@vimil - do we expect a new build soon?

@vimil
Copy link
Member

vimil commented Apr 3, 2019

yes I have released version 0.78 which has the requested changes. My email in github was outdated which is why I couldn't respond sooner.

@rodrigc rodrigc deleted the JENKINS-34617-rodrigc branch April 3, 2019 08:10
@rodrigc
Copy link
Contributor Author

rodrigc commented Apr 3, 2019

@vimil Thanks!

@rodrigc
Copy link
Contributor Author

rodrigc commented Apr 5, 2019

@vimil If possible please update your contact email in GitHub to one that is accurate.

@andreatera
Copy link

do you know if a newer plugin version will be available from Jenkins including this commit? I see that in the Jenkins Plugin Manager latest version is 1.6.0 while this project has 0.78 (including this commit).

@afrancoc2000
Copy link

@andreatera you are confusing extended choice plugin and extensible choice plugin, this page is for extended choice plugin and the latest version is 0.78. The extensible choice plugin latest version is 1.6.0

@andreatera
Copy link

andreatera commented Jun 4, 2019

@afrancoc2000 aaah that's why 😄 sorry but I was confused by latest post on this page: https://wiki.jenkins.io/display/JENKINS/Extensible+Choice+Parameter+plugin

Thanks a lot!

@molexx
Copy link

molexx commented Nov 21, 2019

When configured manually in the UI the bindings passed to groovy contains the Job under key currentProject but when used from pipeline it is not present?

@zentavr where is your property ${lambdasArtifactsListFile} defined/set please?

@vikas027
Copy link

I've installed v0.78 of the plugin on Jenkins 2.204.2 and restarted Jenkins, but it throws below error while using it.

No signature of method: javaposse.jobdsl.dsl.helpers.BuildParametersContext.extendedChoice() is applicable for argument types: (java.util.LinkedHashMap) values: [[defaultValue:One,Two,Three,Four, description:Some description, ...]]

This is my file

    parameters {
        stringParam('GIT_REPO',"my-repo",'xxx')
        stringParam('GIT_BRANCH',"master",'xxx')
        extendedChoice(
            defaultValue: 'One,Two,Three,Four',
            description: 'Some description',
            multiSelectDelimiter: ',',
            name: 'SAMPLE_EXTENDED_CHOICE',
            quoteValue: false,
            saveJSONParameterToFile: false,
            type: 'PT_CHECKBOX',
            value:'One,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten',
            visibleItemCount: 10
        )
    }

Any ideas how do debug this or maybe I am missing something?

@cheryPeng
Copy link

cheryPeng commented Apr 8, 2020

I've installed v0.78 of the plugin on Jenkins 2.204.2 and restarted Jenkins, but it throws below error while using it.

No signature of method: javaposse.jobdsl.dsl.helpers.BuildParametersContext.extendedChoice() is applicable for argument types: (java.util.LinkedHashMap) values: [[defaultValue:One,Two,Three,Four, description:Some description, ...]]

This is my file

    parameters {
        stringParam('GIT_REPO',"my-repo",'xxx')
        stringParam('GIT_BRANCH',"master",'xxx')
        extendedChoice(
            defaultValue: 'One,Two,Three,Four',
            description: 'Some description',
            multiSelectDelimiter: ',',
            name: 'SAMPLE_EXTENDED_CHOICE',
            quoteValue: false,
            saveJSONParameterToFile: false,
            type: 'PT_CHECKBOX',
            value:'One,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten',
            visibleItemCount: 10
        )
    }

Any ideas how do debug this or maybe I am missing something?

@vikas027 It works fine here with jenkins version 2.150.2, and plugin v0.78, maybe you just need to approve the script requested by com.cwctravel.hudson.plugins.extended_choice_parameter.ExtendedChoiceParameterDefinition
in In-process Script Approval console?

@vikas027
Copy link

vikas027 commented Apr 8, 2020

@cheryPeng - Sorry, I do not have my old environment to test it now but I remember, I did checked the In-process Script Approval console when I had this issue.

@derbenevivan
Copy link

same as for @vikas027
jenkins 2.233
plugin 0.78

dsl:

job('example') {
  parameters {
        stringParam('GIT_REPO',"my-repo",'xxx')
        stringParam('GIT_BRANCH',"master",'xxx')
    	extendedChoice {
            name("BRANCH")
            type("Single Select")
            visibleItemCount(5)
            multiSelectDelimiter(',')
            groovyScript("return new File(\"/var/jenkins_home/userContent/message-service-branches.list\").readLines()")
            defaultValue("zzz")
        }
    }
}

extendedChoice() returns
No signature of method: javaposse.jobdsl.dsl.helpers.BuildParametersContext.extendedChoice() is applicable for argument types: (java.util.LinkedHashMap)

if i use extendedChoice{}, it requires all of the fields to be set, which is definately not a proper behaviour:
ERROR: (script, line 5) the following options are required and must be specified: value, projectName, propertyFile, groovyScriptFile, bindings, groovyClasspath, propertyKey, defaultPropertyFile, defaultGroovyScript, defaultGroovyScriptFile, defaultBindings, defaultGroovyClasspath, defaultPropertyKey, descriptionPropertyValue, descriptionPropertyFile, descriptionGroovyScript, descriptionGroovyScriptFile, descriptionBindings, descriptionGroovyClasspath, descriptionPropertyKey, javascriptFile, javascript, saveJSONParameterToFile, quoteValue, description

@kilabyte
Copy link

kilabyte commented May 8, 2020

Also seeing the same error for using extendedChoice() using version 0.78 on jenkins versions 2.204.5.

@pavoltravnik
Copy link

Also seeing the same error for using extendedChoice() using version 0.78 on jenkins version 2.255

@lukasbar
Copy link

Error still exist in 0.82 version

@sknight80
Copy link

Sorry, but it does not work for me at all. :(. Can you actually define extendedChoice parameter via JobDSL?

@betterthanbreakfast
Copy link

betterthanbreakfast commented May 18, 2021

Sorry, but it does not work for me at all. :(. Can you actually define extendedChoice parameter via JobDSL?

yes, actually you can. Here's complete example how to fetch available versions from JFrog Artifactory via groovy script:

import com.cwctravel.hudson.plugins.extended_choice_parameter.ExtendedChoiceParameterDefinition

def SingleSelect (String name, int visibleItemCnt=5, String groovyScript, String description='', String delimiter=',') {

    // default same as number of values
    return new ExtendedChoiceParameterDefinition(
        name, //name,
        "PT_SINGLE_SELECT", //type
        "", //value
        "", //projectName
        "", //propertyFile
        groovyScript, //groovyScript
        "", //groovyScriptFile
        "", //bindings
        "", //groovyClasspath
        "", //propertyKey
        "", //defaultValue
        "", //defaultPropertyFile
        "", //defaultGroovyScript
        "", //defaultGroovyScriptFile
        "", //defaultBindings
        "", //defaultGroovyClasspath
        "", //defaultPropertyKey
        "", //descriptionPropertyValue
        "", //descriptionPropertyFile
        "", //descriptionGroovyScript
        "", //descriptionGroovyScriptFile
        "", //descriptionBindings
        "", //descriptionGroovyClasspath
        "", //descriptionPropertyKey
        "", //javascriptFile
        "", //javascript
        false, //saveJSONParameterToFile
        false, //quoteValue
        visibleItemCnt, //visibleItemCount
        description, //description
        delimiter //multiSelectDelimiter
        )
}

def appRelease = SingleSelect(
    "APP_Version", // name
    5, //visible item cnt
    """import groovy.json.JsonSlurper
new JsonSlurper().parseText('https://example.jfrog.io/example/api/search/versions?g=bundle&a=APPBundle&repos=example_repo'.toURL().getText(requestProperties: ['Accept': 'application/json', 'X-Api-Key': 'xxx'])).results.version""", // values
    "", // description
    )

properties(
    [parameters([appRelease])]
)

node {
    echo "${params.APP_Version}"
}

@AnamikaN
Copy link

When I tried to use the above code, I have got the following error,

java.lang.NoSuchMethodError: No such DSL method 'extendedChoice' found among steps [ansiColor, ansiblePlaybook, ansibleVault, archive, bat, build, catchError, checkout, deleteDir, dir, dockerFingerprintFrom, dockerFingerprintRun, dockerNode, echo, emailext, emailextrecipients, envVarsForTool, error, fileExists, getContext, git, input, isUnix, jiraComment, jiraIssueSelector, jiraSearch, junit, library, libraryResource, load, lock, mail, milestone, node, parallel, powershell, properties, publishHTML, pwd, readFile, readTrusted, resolveScm, retry, script, sh, slackSend, sleep, sshagent, stage, stash, step, svn, timeout, timestamps, tm, tool, unarchive, unstash, validateDeclarativePipeline, waitUntil, withContext, withCredentials, withDockerContainer, withDockerRegistry, withDockerServer, withEnv, wrap, writeFile, ws] or symbols [all, allOf, always, ant, antFromApache, antOutcome, antTarget, any, anyOf, apiToken, architecture, archiveArtifacts, artifactManager, attach, authorizationMatrix, batchFile, bitbucket, booleanParam, branch, brokenBuildSuspects, brokenTestsSuspects, buildButton, buildDiscarder, buildingTag, caseInsensitive, caseSensitive, certificate, changeRequest, changelog, changeset, checkoutToSubdirectory, choice, choiceParam, cleanWs, clock, cloud, command, credentials, cron, crumb, culprits, defaultView, demand, developers, disableConcurrentBuilds, disableResume, docker, dockerCert, dockerfile, downloadSettings, downstream, dumb, durabilityHint, envVars, environment, equals, expression, file, fileParam, filePath, fingerprint, frameOptions, freeStyle, freeStyleJob, fromScm, fromSource, git, github, githubPush, gradle, headRegexFilter, headWildcardFilter, hyperlink, hyperlinkToModels, inheriting, inheritingGlobal, installSource, isRestartedRun, jdk, jdkInstaller, jgit, jgitapache, jnlp, jobName, label, lastDuration, lastFailure, lastGrantedAuthorities, lastStable, lastSuccess, legacy, legacySCM, list, local, location, logRotator, loggedInUsersCanDoAnything, masterBuild, maven, maven3Mojos, mavenErrors, mavenMojos, mavenWarnings, modernSCM, myView, newContainerPerStage, node, nodeProperties, nonInheriting, nonStoredPasswordParam, none, not, overrideIndexTriggers, paneStatus, parallelsAlwaysFailFast, parameters, password, pattern, permanent, pipeline-model, pipelineTriggers, plainText, plugin, pollSCM, preserveStashes, projectNamingStrategy, proxy, queueItemAuthenticator, quietPeriod, rateLimitBuilds, recipients, remotingCLI, requestor, run, runParam, schedule, scmRetryCount, scriptApprovalLink, search, security, shell, skipDefaultCheckout, skipStagesAfterUnstable, slackNotifier, slave, sourceRegexFilter, sourceWildcardFilter, ssh, sshUserPrivateKey, stackTrace, standard, status, string, stringParam, swapSpace, tag, text, textParam, tmpSpace, toolLocation, triggeredBy, unsecured, upstream, upstreamDevelopers, usernameColonPassword, usernamePassword, viewsTabBar, weather, withAnt, zfs, zip] or globals [currentBuild, docker, env, params, pipeline, scm]

Looks like Jenkins doesnt support this function yet.?

i am getting the same error. Any suggestions, what could be the issue?

@MioOgbeni
Copy link

same as for @vikas027 jenkins 2.233 plugin 0.78

dsl:

job('example') {
  parameters {
        stringParam('GIT_REPO',"my-repo",'xxx')
        stringParam('GIT_BRANCH',"master",'xxx')
    	extendedChoice {
            name("BRANCH")
            type("Single Select")
            visibleItemCount(5)
            multiSelectDelimiter(',')
            groovyScript("return new File(\"/var/jenkins_home/userContent/message-service-branches.list\").readLines()")
            defaultValue("zzz")
        }
    }
}

extendedChoice() returns No signature of method: javaposse.jobdsl.dsl.helpers.BuildParametersContext.extendedChoice() is applicable for argument types: (java.util.LinkedHashMap)

if i use extendedChoice{}, it requires all of the fields to be set, which is definately not a proper behaviour: ERROR: (script, line 5) the following options are required and must be specified: value, projectName, propertyFile, groovyScriptFile, bindings, groovyClasspath, propertyKey, defaultPropertyFile, defaultGroovyScript, defaultGroovyScriptFile, defaultBindings, defaultGroovyClasspath, defaultPropertyKey, descriptionPropertyValue, descriptionPropertyFile, descriptionGroovyScript, descriptionGroovyScriptFile, descriptionBindings, descriptionGroovyClasspath, descriptionPropertyKey, javascriptFile, javascript, saveJSONParameterToFile, quoteValue, description

Hi, I had a same problem like in quoted post. But I found useful post on job-dsl-plugin github.
https://github.com/jenkinsci/job-dsl-plugin/wiki/Dynamic-DSL

When you will face some of these errors, try to look to your jenkins dsl plugin api definition. When I followed the defined structure its works. In "job/parameters" section you can find all parameters from installed jenkins plugins. extendedChoice included.
http://localhost:8080/plugin/job-dsl/api-viewer/index.html

@zhangguanzhang
Copy link

zhangguanzhang commented Apr 23, 2024

any update ?
version info:

  • Jenkins 2.442
  • plugin version: Extended Choice Parameter Version 381.v360a_25ea_017c
        extendedChoice(
            name: 'severity2', 
            value: 'UNKNOWN,LOW,MEDIUM,HIGH,CRITICAL',
            defaultValue: 'HIGH,CRITICAL',
            quoteValue: false,
            visibleItemCount: 5,
            description: 'scan level',
            type: 'PT_MULTI_SELECT',
            multiSelectDelimiter: ','
        ),

log:

java.lang.NoSuchMethodError: No such DSL method 'extendedChoice' found among steps [...]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.