Groovy matching pattern in array - jenkins

I want to match patterns in an array and run tests depending on the environment names.
node('test node'){
stage ('apply terraform') {
// this stage is passing successfully
env_meta = getEnvMeta("test", "${env.ENV_NAME}")
}
stage ('Run Env Tets'){
defChildEnvs = "a1, a2, b1,b2, c1, c2"
switch(env.ENV_NAME) {
case "a":
build job: 'infra_tets', parameters: [
string (name: 'UI_TESTS', value: 'all'),
string (name: 'env', value: env.ENV_NAME)
]
break
}
}
}
env.ENVIROMENT_NAME should return a, b, or c. if the environment is "a" infra_tets build job should start on a1 and a2.

Related

How to use for loop with def list in Jenkins declarative pipeline

I have used for-loop in my script to run one by one which is mentioned in def data it is executing in how many values are given in def data but inside def data the word in not picking and not applying to the sentence.
Help me to slove this issue that help me to slove the original issue
Example
Def data = [ "apple","orange" ]
Stage(create sentence){
Steps{
Script {
For (x in data){
Sh 'the fruit name is ${x}
}
}
}
}
Excepted output
the fruit name is apple
the fruit name is orange
But my output be like
the fruit name is
the fruit name is
To use loop in this case you don't need for, you can simply iterate in the list you have.
To iterate only value:
data.each{
println it
}
OR
data.each {val->
println(val)
}
To iterate Value with index:
data.eachWithIndex{it,index->
println "value " + it + " at index " +index
}
So, final pipeline looks like this.
def data = [ "apple","orange" ]
pipeline {
agent any
stages
{
stage('create sentence')
{
steps
{
script{
data.each {val->
println("the fruit name is " + val)
}
}
}
}
}
}

Jenkinsfile print parameters nicely

We have a Jenkinsfile with parameters declared as follows:
def params = [string(name: 'ENVIRONMENT', value: environment),
string(name: 'VERSION', value: version),
string(name: 'REGION', value: region)]
I'd like to echo these, for example
DEPLOYING: ENVIRONMENT=STAGING, VERSION=1.3.0, REGION=EU
However calling echo "$params" prints:
[#string(name=ENVIRONMENT,value=STAGING), #string(name=VERSION,value=1.3.0), #string(name=REGION,value=EU)]
I tried iterating the array - e.g. :
params.each { echo it } throws UnsupportedOperationException: no known implementation of class java.lang.String is using symbol ‘string’
params.each { echo it.name } throws RejectedAccessException: No such field found: field org.jenkinsci.plugins.structs.describable.UninstantiatedDescribable name
How can I print the params array nicely?
EDIT - from Matt Schuchard's response:
def params = [string(name: 'ENVIRONMENT', value: "STAGING"),
string(name: 'VERSION', value: "1.3.0"),
string(name: 'REGION', value: "EU")]
print "$params"
params.each() { param, value ->
print "Parameter: ${param}, Value: ${value}"
}
returns (i.e. Value is all null):
[#string(name=ENVIRONMENT,value=STAGING), #string(name=VERSION,value=1.3.0), #string(name=REGION,value=EU)]
Parameter: #string(name=ENVIRONMENT,value=STAGING), Value: null
Parameter: #string(name=VERSION,value=1.3.0), Value: null
Parameter: #string(name=REGION,value=EU), Value: null
You can use a Groovy map iterator lambda method (such as each) to iterate over the params map. An example follows:
params.each() { param, value ->
print "Parameter: ${param}, Value: ${value}"
}
If you decide to use this directly inside a pipeline block, then this will need to be placed inside a script block when using declarative DSL.
There must be a better way but the following works
Iterating the params array:
1. Cast each parameter to a regular String
2. Extracted the value between #string( VALUE )
3. Split the key/value pairs first by comma ','
4. Then split each side of the above by equals '='
5. Concatenate the second argument
def pretty(params) {
def s = ""
params.each { param ->
def a = ("${param}" =~ /^#string\((.+)\)$/)[ 0 ][ 1 ]
def b = a.split(",")
s = s + b[0].split("=")[1] + "=" + b[1].split("=")[1] + "\n"
}
return s
}
Returns:
ENVIRONMENT=STAGING
VERSION=1.3.0
REGION=EU
is params goal is to parameterized the build?
if this is the case, you can use parameters directive
The parameters directive provides a list of parameters that a user
should provide when triggering the Pipeline.
The values for these
user-specified parameters are made available to Pipeline steps via the
params object.
declerative pipeline:
Declarative Pipeline supports parameters out-of-the-box, allowing the
Pipeline to accept user-specified parameters at runtime via the
parameters directive.
parameters {
string(name: 'ENVIRONMENT', defaultValue: 'STAGING', description: 'Environment to test. e.g: production/develop'),
string(name: 'VERSION', defaultValue: '1.3.0', description: 'Version to run'),
string(name: 'REGION', defaultValue: 'EU', description: 'Region')
}
scripted pipeline:
Configuring parameters with Scripted Pipeline is
done with the properties step, which can be found in the Snippet
Generator
properties([
parameters([
string(name: 'ENVIRONMENT', defaultValue: 'STAGING', description: 'Environment to test. e.g: production/develop'),
string(name: 'VERSION', defaultValue: '1.3.0', description: 'Version to run'),
string(name: 'REGION', defaultValue: 'EU', description: 'Region')
])
])
now, those parameters are accessible as members of the params variable
so, then you can simply use:
params.each() { param, value ->
print "Parameter: ${param}, Value: ${value}"
}

How can I pass MatrixCombinationsParameterValue with simple filter in groovy pipeline

I have a job with matrix project, I added ElasticAxis name:label
I also added a matrix combinations parameter name: labelFilter
I want to run the job from groovy pipeline with filter label == "PA16"
This call is not working for me:
[$class: 'MatrixCombinationsParameterValue', name: 'labelFilter', value: 'label=="PA16"']
The question is: What is the correct syntax to call the matrix combinations parameter?
I have few branches, each branch should run with specific label, the pipeline gets the branch name and run a job in jenkins with the name of the label. Lets say I want to run the job with the label "PA16" so I add this code to groovy pipeline file:
build job: 'test_matrix',
parameters: [
string(name: 'RndBranch', value: RndBranch),
string(name: 'BuildNumber', value: PAVersion),
string(name: 'Auto_Build_Path', value: autoFolder),
string(name: 'Installer_folder', value: Installer_folder),
string(name: 'RabbitMQ_Server', value: rabbitMQServer),
string(name: 'QueName', value: qName),
[$class: 'MatrixCombinationsParameterValue', name: 'labelFilter', filter: 'label=="PA16"']
]
For Jenkins pipeline please use matrix instead. For example:
stage ('TestMatrix') {
matrix {
axes {
axis {
name 'labelFilter'
values 'PA16', 'PA17', 'PA18'
}
axis {
name 'otherFilter'
values 'Filter1', 'Filter2', 'Filter3'
}
}
stages {
stage ('Doing what you want') {
steps { echo "Doing what I want"}
}
}
}
}
You can read more at following document about matrix or here

Jenkins pipeline conditional stage using "When" for choice parameters

I am trying to build a jenkins pipeline where I have a choice parameter with n choices and want to create a stage which does something when some values from the choice parameter are selected
I have something like below but doesn't seem to work.
#!/usr/bin/env groovy
pipeline {
agent any
parameters {
choice(
choices: 'a\nb\n\c\n\d\ne\nf',
description: 'name of the student',
name: 'name'
)
}
stages {
stage ('callNames') {
when {
expression { params.name == 'a|d|f' }
}
steps{
echo "selected name is: ${name}"
//do something
}
}
}
}
So, I want to do something when the selected values for the parameter name are either a or d of f
For the above, I get no errors but I am seeing this in the console output
Stage 'callNames' skipped due to when conditional when I select the value a/d/f during the build
Please let me know what's missing here
Thanks in advance
Your when expression has an error. If your parameter's name value is 'a', you are comparing strings 'a' == 'a|d|f' in your code, which is false.
You probably want to do
when {
expression {
params.name == 'a' ||
params.name == 'd' ||
params.name == 'f'
}
}
Or, if you prefer oneliner, you can use regular expression
when {
expression {
params.name ==~ /a|d|f/
}
}

How do i pass named parameters (not all string values) to another job in Jenkins Pipeline?

I want to pass a bunch of parameters that are named, some of which are also Maps of named parameters into another job. The below does not work:
node
{
stage ('Deploying')
{
build job: 'job-runner',
serverSetup: [test: 'test'],
jobs: [
myJob: "true"
],
runType: [test: "test"]
}
}
I want the called job to be able to do all of the following:
parameters.serverSetup.test
if ( parameters.jobs.MyJob == true )
parameters.runtype.test
How would I do that?
With the build job function, you can pass parameters. Ex : build job: 'job-runner', parameters: [[$class: 'StringParameterValue', name: 'string1', value: param1], [$class: 'BooleanParameterValue', name: 'myJob', value: params.myJob]]

Resources