In Jenkins pipeline parameters, auto populate the target environment based on the section of environment.
If environment select the 'Test' and Target Environment should be populate 'Test-US' and 'Test-UK'
If environment select the 'Dev' and Target Environment should be populate 'Dev-US' and 'Dev-UK'
pipeline{
parameters {
choice(name: 'Environment' choices: ['Test', 'Dev'])
choice(name: 'Target Environment' choices: ['Test-US', 'Test-UK', 'Dev-US', 'Dev-UK'])
}
stage('build') {
steps{
script {
echo 'executing.'
} } } }
Any help would be appreciated, Thanks in advance!
You can use Jenkins Active Choice plugin for such purpose. See the link below. There are some detailed examples that could be quite similar to your case.
https://plugins.jenkins.io/uno-choice/
Related
I have a pipeline parameterized by env which takes specific values shown below. The parameter is used in the script and cannot change. But the admin tells me that the labels for the agent have to depend on the parameter env and another fixed one (e.G. LABELX).
The problem I encounter is that, while the script requires exactly the values shown below, the label for the agent is not always ${params.env}, but in one case there's a mapping/translation to be made.
This is the extremely reduced groovy script:
pipeline {
agent {label "${params.env} && LABELX"}
parameters {
choice(
name: 'env',
choices: ['development', 'staging', 'production'],
)
}
stages {
stage('Process') {
steps {
sh """
# use ${params.env} in bash script
""""
}
}
}
}
The mapping I need is as follows:
env
label
development
development
staging
test
production
production
How can I replace the parameter staging with the label test before choosing an agent? I cannot do that in a script, because scripts are run by agents... I have to somehow do this before, inside the ${params.env} maybe. Or do I need an additional parameter (params.label)?
One way to solve it is to create a constant label mapping before your pipeline, and then use it in your pipeline to retrieve the needed value.
Something like:
LABELS = ['development':'development', 'staging':'test', 'production':'production']
pipeline {
agent {
label "${LABELS[params.env]} && LABELX"
}
parameters {
choice(
name: 'env',
choices: ['development', 'staging', 'production'],
)
}
stages {
stage('Process') {
steps {
sh """
# use ${params.env} in bash script
"""
}
}
}
}
By the way, it is not recommended to call your parameter env as it may override or collide in some cases with the default env map that contains all the environment parameters of the job, including those defined in the environment directive.
I am working on creating a single Jenkins job that allows you to pick the GitHub project and then select the branch you would like to run your SonarQube tests on.
So far I have been able to create a job that ONLY runs against the Master build of each project.
Does anyone have any experience creating something like this?
Thanks!
You need to parametrize your build.
You will have to make gitproject and gitBranch as a parameter this will make you select the project you want to run and select the branch too. Here is an example
pipeline {
agent {
node {
label any
}
}
parameters {
choice(
name: 'PLATFORM',
choices:"Test\nArt19-Data-Pipeline\nBrightcove-Report\nBrightcove-Video\nData-Delivery\nGlobal_Facebook_Engagement_Score\nGoogle-Analytics-Data-Pipeline\nInstagram-Data-Pipeline\nTwitter-Analytics\nTwitter-Data-Pipeline\nYoutube-Data",
description: "Choose the lambda function to deploy or rollback")
choice(
name: 'STAGE',
choices:"dev\nstag",
description: "Choose the lambda function to deploy or rollback")
}
stages {
stage("Git CheckOut") {
steps {
//CheckOut from the repository
//git credentialsId: 'svc.gitlab',branch:'master', url: 'git#git.yourProjectURL/yourProjectName.git'
echo " Parameters are ${PLATFORM}"
echo " STAGE IS ${STAGE}"
}
}
}
}
All you need is replace the 'master' with a a paramter and the 'yourProjectName' with another paramter instead of the one i used as example
Our Jenkins setup consists of master nodes and different / dedicated worker nodes for running jobs in dev, test and prod environment. How do I go about creating a scripted pipeline code that allows users to select environment (possibly from master node) and depending upon the environment selected would execute the rest of the job in the node selected? Here is my initial thought:
stage('Select environment ') {
script {
def userInput = input(id: 'userInput', message: 'Merge to?',
parameters: [[$class: 'ChoiceParameterDefinition', defaultValue: 'strDef',
description:'describing choices', name:'Env', choices: "dev\ntest\nprod"]
])
println(userInput);
}
echo "Environment here ${params.Env}" // prints null here
stage("Build") {
node(${params.Env}) { // schedule job based upon the environment selected earlier
echo "My test here"
}
}
}
I am in the right path or should I be looking at something else?
Another follow up question is that the job that is running on the worker node also requires additional user input. Is there a way to combine the user input in one go such that the users would not be prompted with multiple user screens?
If you pass the environment as a build parameter when kicking off the job, and you have appropriate labels on your nodes, you could do something like:
agent = params.WHAT_NODE
agentLabels = "deploy && ${agent}"
pipeline {
agent { label agentLabels }
....
}
Ended up doing the following for scripted pipeline:
The code for selecting environment can be run on any node (whether master or slaves with agent running). The parameter can be injected into an environment variable: env..
node {
stage('Select Environment'){
env.Env = input(id: 'userInput', message: 'Select Environment',
parameters: [[$class: 'ChoiceParameterDefinition',
defaultValue: 'strDef',
description:'describing choices',
name:'Env',
choices: "jen-dev-worker\njen-test-worker\njen-prod-worker"]
])
println(env.Env);
}
stage('Display Environment') {
println(env.Env);
}
}
The following code snippet ensures that script would be executed on the environment selected in the last step. Requires Jenkins workers with labels: jen-dev-worker, jen-test-worker, jen-prod-worker) available.
node (env.Env) {
echo "Hello world, I am running on ${env.Env}"
}
I want to set some jenkins environment variables in run time based on my computation. How can i set this run-time in my jenkinsfile's step section.
for example: based on my calculation i get abc=1. How can i set this in real time in my jenkinsfile's step section so that i can use it later by calling $abc.
I am declaring my pipeline and environment variables as explained here:
https://jenkins.io/doc/pipeline/tour/environment/
i'm using Jenkins ver. 2.41
Here an example how to set variables and use it in the same Jenkinsfile.
The Variable versionToDeploy will be used by the build job step.
pipeline {
agent any
stages {
stage('Example') {
steps {
echo 'build the artifacts'
script {
versionToDeploy = '2.3.0'
}
}
}
}
post {
success {
echo 'start deploy job'
build job: 'pipeline-declarative-multi-job-deploy', parameters: [[$class: 'StringParameterValue', name: 'version', value: versionToDeploy]]
}
}
}
How do I invoke Global environment variables in Jenkinsfile?
For example, if I have a variable -
name:credentialsId
value:xxxx-xxxx-xxxxx-xxxxxxxxx
How do I use it in the groovy script?
I tried ${credentialsId}, but it didn't work. It will just give error:
java.lang.NoSuchMethodError: No such DSL method '$' found among steps [ArtifactoryGradleBuild, ........
In a Jenkinsfile, you have the "Working with the Environment" which mentions:
The full list of environment variables accessible from within Jenkins Pipeline is documented at localhost:8080/pipeline-syntax/globals#env,
The syntax is ${env.xxx} as in:
node {
echo "Running ${env.BUILD_ID} on ${env.JENKINS_URL}"
}
See also "Managing the Environment".
How can I pass the Global variables to the Jenkinsfile?
When I say Global variables - I mean in
Jenkins -> Manage Jenkins -> Configure System -> Global properties -> Environment variables
See "Setting environment variables"
Setting an environment variable within a Jenkins Pipeline can be done with the withEnv step, which allows overriding specified environment variables for a given block of Pipeline Script, for example:
Jenkinsfile (Pipeline Script)
node {
/* .. snip .. */
withEnv(["NAME=value"]) {
... your job
}
}
When referring to env in Groovy scope, simply use env.VARIABLE_NAME, for example to pass on BUILD_NUMBER of upstream job to a triggered job:
stage ('Starting job') {
build job: 'TriggerTest', parameters: [
[$class: 'StringParameterValue', name: 'upstream_build_number', value: env.BUILD_NUMBER]
]
}
Scripted pipeline
To read an environment variable whose name you know, use env.NAME
To read an environment variable whose name is not known until runtime use env.getProperty(name).
For example, a value from a YAML config file represents an environment variable name:
config.yaml (in workspace)
myconfig:
key: JOB_DISPLAY_URL
Jenkinsfile
node {
println("Running job ${env.JOB_NAME}")
def config = readYaml(file:'config.yaml')
def value = env.getProperty(config.myconfig.key)
println("Value of property ${config.myconfig.key} is ${value}")
}
For getting values all env.VAR, env['VAR'], env.getProperty('VAR') are fine.
For setting values the only safe way at the moment is withEnv. If you try to assign values to env.VAR it may not work in some cases like for parallel pipelines (like in JENKINS-59871).
Another syntax is $ENV:xxxx
node {
echo "Running $ENV.BUILD_ID on $ENV.JENKINS_URL" }
This worked for me