Using Key Value Pair in Jenkins - jenkins

This is my requirement to have parameters in Jenkins:
1. User selects 3 Values from Dropdown: DEV, QA, PROD
2. Upon selection I need to return single value as parameter as like this:
If DEV selected, return "Development http://dev.com 1"
If QA selected, return "QA http://qa.com 2"
If PROD selected, return "Production http://prod.com 3"
3. Once the value is returned in a variable, I will use that variable value in next step of 'Windows batch command'.
Where and How can define Key/Values. I tried to use Extended Choice Parameter plugin, but not sure how to do this.

I have managed to get the keys/values with a dropdown select parameter working with the Active Choices Plugin, it's not as complicated as the other answer here, and it actually buried in the comments on the plugin page itself.
To get a key/value pair select dropdown list parameter in Jenkins (i.e. show a human readable value, but pass a different key to the build. You simply need to use a map rather than a list when writing your groovy script. The map key is what the parameter will be set to if the user selects this option. The map value is what will be actually displayed to the user in the dropdown list.
For example the script: return ['Key1':'Display 1', 'Key2':'Display 2', 'Key3':'Display 3'] will display a dropdown containing: Display1, Display2 and Display3 to the user. However the build parameter will actually be set to Key1, Key2 or Key3 depending on what is selected.
For this specific question, here are the steps.
Ensure you have the Active Choices Plugin installed.
Open the configuration of your Jenkins job, select This project is parameterised.
Click Add Parameter and select Active Choices Parameter.
Name your parameter and click the Groovy Script check box.
In Groovy Script enter content: return ['Development http://dev.com 1':'DEV', 'QA http://qa.com 2':'QA', 'Production http://prod.com 3':'PROD'] For this example the user will see a dropdown with 3 options: DEV, QA, and PROD. The value passed for this parameter will be Development http://dev.com 1 etc. Now having a parameter with space and URLs may cause issue depending on how you use it later on in the build, but the concept is really what I'm trying to illustrate.

This can be achieved using the Active choice plugin, Find below the link and the image for your reference
Plugin reference: https://wiki.jenkins-ci.org/display/JENKINS/Active+Choices+Plugin
Another method without any plugins
Using shell script this can be achieved
Add a build step as shell script and add the below script that will return your values. Lets say the dropdown paramater name is "env"
if [ $env == "DEV" ]
then
url = "Development http://dev.com 1"
elif [ $env == "QA" ]
then
url = "QA http://qa.com 2"
elif [ $env == "PROD" ]
then
url = "Production http://prod.com 3"
fi
The $url variable will be having the expected value that can be used in your next build steps
Shell Script Reference: http://www.tutorialspoint.com/unix/if-elif-statement.htm

You can do the mapping in a groovy script. If you have a parameter named InputParam, you can map it to a new parameter called OutParam in a System Groovy Script like so:
import hudson.model.*
def parameterMap=[:]
parameterMap.put('DEV','Development http://dev.com 1')
parameterMap.put('QA','QA http://qa.com 2')
parameterMap.put('PROD','Production http://prod.com 3')
def buildMap = build.getBuildVariables()
def inputValue=buildMap['InputParam']
buildMap['OutParam']=parameterMap[inputValue]
setBuildParameters(buildMap)
def setBuildParameters(map) {
def npl = new ArrayList<StringParameterValue>()
for (e in map) {
npl.add(new StringParameterValue(e.key.toString(), e.value.toString()))
}
def newPa = null
def oldPa = build.getAction(ParametersAction.class)
if (oldPa != null) {
build.actions.remove(oldPa)
newPa = oldPa.createUpdated(npl)
} else {
newPa = new ParametersAction(npl)
}
build.actions.add(newPa)
}
Choose Execute system Groovy script as the first build action. You can then access the output param as an environmental variable in the windows shell, eg.
ECHO %OUTPARAM%

Related

Jenkins Parameterized Project For Multiple Parameters

I have Jenkins Pipeline which is triggering for different projects. However the only difference in all the pipelines is just the name.
So I have added a parameter ${project} in parameter of jenkins and assigned it a value of the name of the project.
We have a number of projects and I am trying to find a better way through which I can achieve this.
I am thinking how can we make the parameter run with different parameters for all the projects without actually creating different projects under jenkins.
I am pasting some screenshot for you to understand what exactly I want to achieve.
As mentioned here, this is a radioserver project, having a pipeline which has ${project} in it.
How can I give multiple values to that {project} from single jenkins job?
IF you have any doubts please message me or add a comment.
You can see those 2 projects I have created, it has all the contents same but just the parameterized value is different, I am thinking how can I give the different value to that parameter.
As you can see the 2 images is having their default value as radioserver, nrcuup. How can I combine them and make them run seemlessly ?
I hope this will help. Let me know if any changes required in answer.
You can use conditions in Jenkins. Based on the value of ${PROJECT}, you can then execute the particular stage.
Here is a simple example of a pipeline, where I have given choices to select the value of parameter PROJECT i.e. test1, test2 and test3.
So, whenever you select test1, jenkins job will execute the stages that are based on test1
Sample pipeline code
pipeline {
agent any
parameters {
choice(
choices: ['test1' , 'test2', 'test3'],
description: 'PROJECT NAME',
name: 'PROJECT')
}
stages {
stage ('PROJECT 1 RUN') {
when {
expression { params.PROJECT == 'test1' }
}
steps {
echo "Hello, test1"
}
}
stage ('PROJECT 2 RUN') {
when {
expression { params.PROJECT == 'test2' }
}
steps {
echo "Hello, test2"
}
}
}
}
Output:
when test1 is selected
when test2 is selected
Updated Answer
Yes, it is possible to trigger the job periodically with a specific parameter value using the Jenkins plugin Parameterized Scheduler
After you save the project with some parameters (like above mentioned pipeline code), go back again to the Configure and under Build Trigger, you can see the option of Build periodically with parameters
Example:
I will here run the job for PROJECT=test1 every even minutes and PROJECT=test2 every uneven minutes. So, below is the configuration
*/2 * * * * %PROJECT=test1
1-59/2 * * * * %PROJECT=test2
Please change the crontab values according to your need
Output:

Is it possible to set the a variable group scope using DevOps CLI or via REST

I am able to add/modify DevOps release definitions through a combination of CLI and CLI REST methods. The release definition object does not include (as far as I can tell) a property that controls the variable group scope. The release definition itself takes an array of variable group ID's but there is also the scope of the variable group within the context of the release definition. Where is that?
Is there support to access the variable group scope property in the CLI or CLI REST interface? The image below shows the interface from the portal in azure. Selecting the ellipses (...) you can "change scope" where a list of stages is displayed. You than save and then save the release definition.
I captured fiddler output but the body post was huge and not very helpful, I didn't see anything related to a list of scopes. but obviously this can be done. I'm just not sure about doing so via CLI or REST.
Edit: Here is a view of the script. There is no "scope", which should contain a list of environment names, anywhere in the release definition that I can see. Each environment name (aka stage) contains a number of variable groups associated with each environment.
$sourcedefinition = getreleasedefinitionrequestwithpat $reldefid $personalAccesstoken $org $project | select -Last 1
Write-Host "Root VariableGroups: " $sourcedefinition.variableGroups
$result = #()
#search each stage in the pipeline
foreach($item in $sourcedefinition.environments)
{
Write-Host ""
Write-Host "environment name: "$item.name
Write-Host "environment variable groups: "$item.variableGroups
}
To help clarify, the scope I seek cannot be in the environments collection as this is specific to each element (stage). The scope is set at the release definition level for a given variable group (again refer to the image).
I use this API to get the Definitions of my release and find that the values of variableGroups in ReleaseDefinition and in ReleaseDefinitionEnvironment are different when the scopes are different.
Then I think if we want to change the scope via REST API, we just need to change the variableGroups and update the Definitions. We can use this API to update the Definitions.
Edit:
For example, I want to change my scope from Release to Stage, I use the API like below:
PUT https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/definitions?api-version=6.1-preview.4
Request Body: (I get this from the first Get Definitions API Response Body and make some changes to use it)
{
"source":"userInterface",
"revision":6,
...
"lastRelease": {
"id": 1,
...
},
...
"variables":{
},
"variableGroups":[],
"environments":[
{
"name": "Stage 1",
...
"variables":{
},
"variableGroups":[
4
],
...
}
],
...
}
Note:
Please use your own newer revision.
The id value in lastRelease is your release definitionId.
Specify the stage name in environments name.
The variableGroups value in environments is the id of the variable group you want to change scope.

How to pass Value inserted in text box of Active choice reactive parameter to job

When I'm in "build with parameters" before starting job, I want to pass the value entered in a textbox to the Job. I´m using Active choice and Active choice reactive parameter like this:
This is the groovy script which I then use to run job and show output. But I´m getting NULL on echo command.
node {
def commit = params.val
stage ('Pulling code from Bitbucket') {
git branch: 'master',
credentialsId: '2bbc73c4-254e-45bd-85f4-6a169699310c',
url: 'git#bitbucket.org:repo/test.git'
sh (""" echo ${commit}""")
}
}
Which is the correct way to pass parameter into build ?
From your output, you have defined a parameter named ID1 that references some other parameter named OPTIONS. The correct way to reference these parameters is params.ID1 and params.OPTIONS. I can't see a parameter named val that can be addressed by params.val.

I have a Jenkins global variable in a string - how do I evaluate it?

I need to accept all kinds of global Jenkins variables as strings (basically as parameters to ansible like system - a template stored in \vars).
def proof = "\"${params.REPOSITORY_NAME}\""
echo proof
def before = "\"\${params.REPOSITORY_NAME}\""
echo before
def after = Eval.me(before)
echo after
The result is:
[Pipeline] echo
"asfd"
[Pipeline] echo
"${params.REPOSITORY_NAME}"
groovy.lang.MissingPropertyException: No such property: params for class: Script1
the first echo proves that the param value actually exists.
the second echo is the what the input actually looks like.
the third echo should have emitted asdf instead I get the exception.
Any ideas? I'm hours into this :-(
You may want to check:
groovy: Have a field name, need to set value and don't want to use switch
1st Variant
In case you have: xyz="REPOSITORY_NAME" and want the value of the parameter REPOSITORY_NAME you can simply use:
def xyz = "REPOSITORY_NAME"
echo params."$xyz" // will print the value of params.REPOSITORY_NAME
In case if your variable xyz must hold the full string including params. you could use the following solution
#NonCPS
def split(string) {
string.split(/\./)
}
def xyz = "params.REPOSITORY_NAME"
def splitString = split(xyz)
echo this."${splitString[0]}"."${splitString[1]}" // will print the value of params.REPOSITORY_NAME
2nd Variant
In case you want to specify an environment variable name as parameter you can use:
env.“${params.REPOSITORY_NAME}”
In plain groovy env[params.REPOSITORY_NAME] would work but in pipeline this one would not work inside the sandbox.
That way you first retrieve the value of REPOSITORY_NAME and than use it as key to a environment variable.
Using directly env.REPOSITORY_NAME will not be the same as it would try to use REPOSITORY_NAME itself as the key.
E.g. say you have a job named MyJob with the following script:
assert(params.MyParameter == "JOB_NAME")
echo env."${params.MyParameter}"
assert(env."${params.MyParameter}" == 'MyJob')
This will print the name of the job (MyJob) to the console assuming you did set the MyParameter parameter to JOB_NAME. Both asserts will pass.
Please don’t forget to open a node{} block first in case you want to retrieve the environment of that very node.
After trying all those solutions, found out that this works for my problem (which sounds VERY similar to the question asked - not exactly sure though):
${env[REPOSITORY_NAME]}

Dynamic Choice Parameter not populated: Jenkins job + Groovy script

I am trying to create a dynamic choice parameter that will be populated by the resulting values of a groovy script.
The following code works and lists the contents of a dir:
new File("/tmp/testing/source/").eachFile() { file->
println file.getName()
}
I created a new jenkins project, and entered the menu 'Configure' where I selected This project is parameterized
When I save and try to build with parameters nothing has been parsed from the groovy script
Solved with the following code:
list = []
def process = "ls /tmp/testing/source".execute()
process.text.eachLine {list.add it}
return list

Resources