Using Function in JenkinsFile Parameter Description - jenkins-pipeline

I am trying to add a function in JenkinsFile Declarative pipelines parameter's description but struggling to make it work.
Idea is to have a Jenkins Job specific for the environment. and would like to see the choice parameter to show environment name in the description of the variable.
My pipeline looks like this
def check_env = app_env(ENVS, env.JOB_NAME)
pipeline {
agent { label 'master' }
options {
disableConcurrentBuilds()
buildDiscarder(logRotator(numToKeepStr: '20'))
timestamps()
}
parameters{
string(name: 'myVariable', defaultValue: "/", description: 'Enter Path To App e.g / OR /dummy_path for ' {check_env} )
}
stages{
stage('Running App') {
agent {
docker {
image 'myApp:latest'
}
}
steps{
script{
sh label: 'App', script: "echo "App is running in ${check_env} "
}
}
}
}
}
}
I have tried multiple combinations for check_env e.g check_env, check_env(), ${check_env} function but none of them worked.

String Interpolation
I believe this is simply a String Interpolation issue. Notice my use of double quotes below
parameters{
string(name: 'myVariable', defaultValue: "/", description: "Enter Path To App e.g / OR /dummy_path for ${check_env}")
}
Your build page should then interpolate your variable
To test I simply set def check_env = 'live' since I do not have the code for your method

Related

Change the parameter values in a Jenkins Pipeline

How to map the parameter values to a different value and then execute it inside the pipeline.
parameters {
choice(name: 'SIMULATION_ID',
choices: 'GatlingDemoblaze\nFrontlineSampleBasic\nGatlingDemoStoreNormalLoadTest',
description: 'Simulations')
}
How to map the value of 'GatlingDemoblaze' to '438740439023874' so that the it will be the latter which goes inside the ${params.SIMULATION_ID}? Can we do this with a simple groovy code?
gatlingFrontLineLauncherStep credentialId: '', simulationId:"${params.SIMULATION_ID}"
Thanks for the help.
As suggested in the comments the best approach will be to use the Extensible Choice Parameter Plugin and define the needed key-value pairs, however if you don't want to use the plugin you can create the mapping using groovy in the pipeline script and use it.
For that you have several options:
If you need it for a single stage you can define the map inside a script block and use it in that stage:
pipeline {
agent any
parameters {
choice(name: 'SIMULATION_ID', description: 'Simulations',
choices: ['GatlingDemoblaze', 'FrontlineSampleBasic', 'GatlingDemoStoreNormalLoadTest'])
}
stages {
stage('Build') {
steps {
script {
def mappings = ['GatlingDemoblaze': '111', 'FrontlineSampleBasic': '222', 'GatlingDemoStoreNormalLoadTest': '333']
gatlingFrontLineLauncherStep credentialId: '', simulationId: mappings[params.SIMULATION_ID]
}
}
}
}
}
You can also define it as a global parameter that will be available in all stages (and then you don't need the script directive):
mappings = ['GatlingDemoblaze': '111', 'FrontlineSampleBasic': '222', 'GatlingDemoStoreNormalLoadTest': '333']
pipeline {
agent any
parameters {
choice(name: 'SIMULATION_ID', description: 'Simulations',
choices: ['GatlingDemoblaze', 'FrontlineSampleBasic', 'GatlingDemoStoreNormalLoadTest'])
}
stages {
stage('Build') {
steps {
gatlingFrontLineLauncherStep credentialId: '', simulationId: mappings[params.SIMULATION_ID]
}
}
}
}
and another options is to set these values in the environment directive:
pipeline {
agent any
parameters {
choice(name: 'SIMULATION_ID', description: 'Simulations',
choices: ['GatlingDemoblaze', 'FrontlineSampleBasic', 'GatlingDemoStoreNormalLoadTest'])
}
environment{
GatlingDemoblaze = '111'
FrontlineSampleBasic = '222'
GatlingDemoStoreNormalLoadTest = '333'
}
stages {
stage('Build') {
steps {
gatlingFrontLineLauncherStep credentialId: '', simulationId: env[params.SIMULATION_ID]
}
}
}
}

Jenkins custom pipeline and how to add property to be set in jenkinsfile

I'm trying to create a custom pipeline with groovy but I can't find anywhere on the web where it is discussed how to add a property that can be set in the jenkinsfile. I'm trying to add a curl command but need the URL to be set in the jenkinsfile because it will be different for each build.
Can anyone explain how that should be done or links where it has been discussed?
Example Jenkinsfile:
msBuildPipelinePlugin
{
curl_url = "http://webhook.url.com"
}
custom pipeline groovy code:
def response = sh(script: 'curl -i -X POST -H 'Content-Type: application/json' -d '{"text","Jenkins Info.\nThis is more text"}' curl_url, returnStdout: true)
Thanks
If you want to specify the URL as a string during every build, you can do either of the following:
Declarative Pipeline
Use the parameters {} directive:
pipeline {
agent {
label 'rhel-7'
}
parameters {
string(
name: 'CURL_URL',
defaultValue: 'http://www.google.com',
description: 'Enter the URL for file download'
)
}
stages {
stage('download-file') {
steps {
echo "The URL is ${params.CURL_URL}"
}
}
}
}
Scripted Pipeline
Use the properties([parameters([...])]) step:
parameters([
string(
name: 'CURL_URL',
defaultValue: 'http://www.google.com',
description: 'Enter the URL for file download'
)
])
node('rhel-7') {
stage('download-file') {
echo "The URL is ${params.CURL_URL}"
}
}
You can choose to leave the values of defaultValue and description empty.
Job GUI
Either of the above syntax will be rendered in the GUI as:
I got it to work using
//response is just the output of the curl statement
def response = ["curl", "-i", "-v", "-X", "POST", "--data-urlencode", "payload={\"text\":\"message body\"}", "curl url goes here"].execute().text
Thanks

How to trigger a multiple run in a single pipeline job of jenkins?

I have a pipeline job which run with below pipeline groovy script,
pipeline {
parameters{
string(name: 'Unique_Number', defaultValue: '', description: 'Enter Unique Number')
}
stages {
stage('Build') {
agent { node { label 'Build' } }
steps {
script {
sh build.sh
}
}
stage('Deploy') {
agent { node { label 'Deploy' } }
steps {
script {
sh deploy.sh
}
}
stage('Test') {
agent { node { label 'Test' } }
steps {
script {
sh test.sh
}
}
}
}
I just trigger this job multiple times with different unique ID number as input parameter. So as a result i will have multiple run/build for this job at different stages.
With this, i need to trigger a multiple run/build to be promote to next stage (i.e., from build to deploy or from deploy to test) in this pipeline job as a one single build instead of triggering each and every single run/build to next stage. Is there any possibility?
I was also trying to do the same thing and found no relevant answers. May this help to someone.
This will read a file that contains the Jenkins Job name and run them iteratively from one single job.
Please change below code accordingly in your Jenkins.
pipeline {
agent any
stages {
stage('Hello') {
steps {
script{
git branch: 'Your Branch name', credentialsId: 'Your crendiatails', url: ' Your BitBucket Repo URL '
##To read file from workspace which will contain the Jenkins Job Name ###
def filePath = readFile "${WORKSPACE}/ Your File Location"
##To read file line by line ###
def lines = filePath.readLines()
##To iterate and run Jenkins Jobs one by one ####
for (line in lines) {
build(job: "$line/branchName",
parameters:
[string(name: 'vertical', value: "${params.vertical}"),
string(name: 'environment', value: "${params.environment}"),
string(name: 'branch', value: "${params.aerdevops_branch}"),
string(name: 'project', value: "${params.host_project}")
]
)
}
}
}
}
}
}
You can start multiple jobs from one pipeline if you run something as:
build job:"One", wait: false
build job:"Two", wait: false
Your main job starts children pipelines and children pipelines will run in parallel.
You can read PipeLine Build Step documentation for more information.
Also, you can read about the parallel run in declarative pipeline
Here you can find a lot of examples for parallel running

How to access jenkinsfile local environment variables from post steps?

I'm attempting to add a post-build step to my jenkinsfile to apply a label to a build. The Jenkins variables are resolved fine, but the environment variables I've defined globally within the file are not resolved. Here's the relevant bits:
pipeline {
environment {
VERSION_MAJOR = '1'
VERSION_MINOR = '0'
VERSION_PATCH = '0'
}
stages {
stage('Build') {
steps {
echo('Testing p4Tag')
}
}
}
post {
success {
build job: 'Copy-Installers',
parameters: [
//
string(name: 'MASTER_VERSION_MAJOR', value: '${VERSION_MAJOR}'),
string(name: 'MASTER_VERSION_MINOR', value: '${VERSION_MINOR}'),
string(name: 'MASTER_VERSION_FEATURE', value: '${VERSION_PATCH}'),
string(name: 'MASTER_BUILD_NUMBER', value: '${BUILD_NUMBER}'),
string(name: 'COMPONENT_NAME', value: 'Console')
}
}
}
The downstream build fails. Looking at the log it appears the local environment variables are not passed in:
The Build Number name is: ${VERSION_MAJOR}
The Build Number name is: ${VERSION_MINOR}
The Build Number name is: ${VERSION_PATCH}
The Build Number name is: 924
The Build environment name is: Console
Update
I've tried the following variations as well:
value: '${env.VERSION_MAJOR}' - Fails similarly to above
value: '$VERSION_MAJOR' - Fails similarly to above
value: $VERSION_MAJOR - Fails with "no such property" error
Update 2
For what it's worth, these variables can be referenced from the stage section. For instance, this works as expected:
stage('build') {
sh('./Build/build-package.sh $VERSION_MAJOR $VERSION_MINOR $VERSION_PATCH $BUILD_NUMBER')
}

Jenkins: How to use choice parameter in declarative pipeline?

My example:
pipeline {
agent any
parameters {
choice(
name: 'myParameter',
choices: "Option1\Option2",
description: 'interesting stuff' )
}
}
outputs with error:
" unexpected char: '\' " on the line with "choices" "
Following these instructions: https://github.com/jenkinsci/pipeline-model-definition-plugin/wiki/Parametrized-pipelines
Any idea or advice on what I do wrong?
The documentation for declarative jenkins pipelines says:
A choice parameter, for example:
pipeline {
.....
parameters {
choice(name: 'CHOICES', choices: ['one', 'two', 'three'], description: '') }
First one is the default value
You need to use \n instead of \.
See this code:
pipeline {
agent any
parameters {
choice(
name: 'myParameter',
choices: "Option1\nOption2",
description: 'interesting stuff' )
}
}
The arguably most elegant way to separate choices is by using an array like so:
pipeline {
agent any
parameters {
choice(
name: 'Env',
choices: ['DEV', 'QA', 'UAT', 'PROD'],
description: 'Passing the Environment'
)
}
stages {
stage('Environment') {
steps {
echo " The environment is ${params.Env}"
}
}
}
}

Resources