I have a jenkinsfile which is parametrized. Based on the input parameters I want to set certain environment variables. But I m not able to get the syntax right.
parameters {
choice choices: ['insure-base-docker/insure-base', 'insure-ide/insure-sd', 'insure-ide/insure-ansible','insure-ide/ansible-test-vini'], description: 'Auf welche repository sollte die Tag erstellt?', name: 'repository'
choice choices: ['tag', 'branch'], description: 'Tag oder branch erstellen', name: 'git_entity'
string defaultValue: '21.x.x', description: 'Version die als branch oder Tag ersellt werden muss', name: 'version', trim: false
}
environment {
GIT_URL = "${'https://my_repo/scm/'+param.repository+'.git'}"
GIT_BRANCH = "${'Release/'+param.version}"
CHECKOUT_BRANCH = '${${git_entity} == "tag" ? "master" : "develop"}'
}
the env vars are always wrong. How do I set the env vars correctly?
Nowadays, there aren't many differences between parameters and environment variables in Jenkins. Even the way you use them, preceded by the env. keyword, is the same.
Try something like this.
pipeline {
parameters {
choice choices: ['insure-base-docker/insure-base', 'insure-ide/insure-sd', 'insure-ide/insure-ansible','insure-ide/ansible-test-vini'], description: 'Auf welche repository sollte die Tag erstellt?', name: 'GIT_PROJECT'
string defaultValue: '21.x.x', description: 'Version die als branch oder Tag ersellt werden muss', name: 'GIT_BRANCH', trim: false
}
agent any
stages {
stage('Cloning Git repository') {
steps {
script {
git branch: "${env.GIT_BRANCH}", credentialsId: 'MY_GIT_CREDENTIALS_PREVIOUSLY_ADDED_TO_JENKINS', url: "http://github.com/user/${env.GIT_PROJECT}.git"
}
}
}
}
}
You can use as GIT_BRANCH not just branches, but also tags.
Best regards.
I am assuming you are using a freestyle project
here are the steps
Go to Build Environment part and check the option Inject environment variables to the build process
it will open a new set of input boxes.
enter your code in Groovy script
Here am just trying to update the Version and Full version to include the passing parameter say TestParam
here is a sample:
import hudson.model.*
import groovy.io.FileType
def build = Thread.currentThread().executable
def buildNumber = build.number
def workspace = build.getEnvVars()["WORKSPACE"]
def defaultBuildNo = build.getEnvVars()["BUILD_NUMBER"]
println "Hi from Groovy script "
println workspace
println defaultBuildNo
def map = [
"BUILD_NUMBER": defaultBuildNo,
"VERSION" : defaultBuildNo + build.getEnvVars()["TestParam"],
"FULL_VERSION": +defaultBuildNo + "." + build.getEnvVars(["TestParam"]
]
return map
Now in the execute shell part type these and see all will resolve successfully.
Execute shell
echo $TestParam
echo $BUILD_NUMBER
echo $VERSION
echo $FULL_VERSION
Now all these env variables are accessible throughout the Job.
Related
How can I expand ${ENV} variables in Jenkins Pipeline if they are in a string I do not control?
For example I have configured my Pipeline Job to load the Pipeline from a parameterized SCM:
If I now access that branch via scm.branches[0].name inside the Pipeline I am currently getting ${REF}, too.
(The checkout scm part of the pipeline works fine, thats not the problem.)
I have tried the tm() step, but that throws org.jenkinsci.plugins.tokenmacro.MacroEvaluationException: Unrecognized macro 'REF' in '${REF}'
I for example cannot use to update the build name:
currentBuild.displayName = "${scm.branches[0].name} (#$BUILD_NUMBER)"
If REF is an Environment variable you can use String interpolation. Just put the variable into double quotes within the pipeline.
echo "${REF}"
Update
Not sure if there is better groovy way to do this. But following is an option you can use.
steps {
script {
script {
echo "${scm.branches[0].name}"
String branchName = "${scm.branches[0].name}"
String envNameOnly = branchName.substring(2, branchName.length()-1)
def env = System.getenv()[envNameOnly]
echo "$env"
}
}
}
I am using Publish over SSH plugin in Jenkins to deploy the jar file which is created from the build process. I have created a pipeline like this
node {
{
stage('Checkout') {
git([url: '.............', branch: 'myBranch', credentialsId: 'mycredentials'])
}
stage('Build') {
script{
sh 'chmod a+x mvnw'
sh './mvnw clean package'
}
}
stage('Deploy to Server'){
def pom = readMavenPom file: 'pom.xml'
script {
sshPublisher(publishers: [sshPublisherDesc(configName: 'server-instance1',
transfers: [sshTransfer(cleanRemote:true,
sourceFiles: "target/${env.PROJECT_NAME}-${pom.version}.jar",
removePrefix: "target",
remoteDirectory: "${env.PROJECT_NAME}",
execCommand: "mv ${env.PROJECT_NAME}/${env.PROJECT_NAME}-${pom.version}.jar ${env.PROJECT_NAME}/${env.PROJECT_NAME}.jar"),
sshTransfer(
execCommand: "/etc/init.d/${env.PROJECT_NAME} restart -Dspring.profiles.active=${PROFILE}"
)
])
])
}
}
}
}
This works. I have a SSH Server configured under Manage Jenkins >> Configure System >> Publish Over SSH.
Now I want to deploy on multiple servers. Lets say I create multiple ssh configurations by name server-instance1, server-instance2. How do I make this Jenkins job parameterized ? I tried with checking the checkbox and selecting a Choice Parameter. But I am not able to figure out how to make the values for this dropdown come from the SSH server list(instead of hardcoding)
I tried few things as mentioned here(How to Control Parametrized publishing in Jenkins using Publish over SSH plugin's Label field). Unfortunately none of the articles talks about doing this from a pipeline.
Any help is much appreciated.
If you want to select the SSH server name dynamically, you can use the Extended Choice Parameter plugin which allows you to execute groovy code that will create the options for the parameter.
In the plugin you can use the following code to get the values:
import jenkins.model.*
def publish_ssh = Jenkins.instance.getDescriptor("jenkins.plugins.publish_over_ssh.BapSshPublisherPlugin")
configurations = publish_ssh.getHostConfigurations() // get all server configurations
return configurations.collect { it.name } // return the list of all servers
To configure this parameter in you pipeline you can use the following code for scripted pipeline:
properties([
parameters([
extendedChoice(name: 'SERVER', type: 'PT_SINGLE_SELECT', description: 'Server for publishing', visibleItemCount: 10,
groovyScript: '''
import jenkins.model.*
def publish_ssh = Jenkins.instance.getDescriptor("jenkins.plugins.publish_over_ssh.BapSshPublisherPlugin")
return publish_ssh.getHostConfigurations() .collect { it.name }
''')
])
])
Or the following code for declarative pipeline:
pipeline {
agent any
parameters {
extendedChoice(name: 'SERVER', type: 'PT_SINGLE_SELECT', description: 'Server for publishing', visibleItemCount: 10,
groovyScript: '''
import jenkins.model.*
def publish_ssh = Jenkins.instance.getDescriptor("jenkins.plugins.publish_over_ssh.BapSshPublisherPlugin")
return publish_ssh.getHostConfigurations() .collect { it.name }
''')
}
...
}
Once the parameter is defined just use it in your sshPublisher step:
sshPublisher(publishers: [sshPublisherDesc(configName: SERVER, transfers: ...
Another option you can have when using the Extended Choice Parameter is to configure it as Multi-Select instead of Single-Select so a user can then select multiple severs, and you can use the parallel option to publish over all selected servers in parallel.
I'm trying to pass groovy variable to powershell script inside of jenkins pipeline, all in the same place but i don't know how. i tried different ways without success.
I require this to obtain the name of the person who approved the step of PIPELINE and pass it to powershell, which connects with SQL SERVER
stage('Step1'){
steps{
script{
def approverDEV
approverDEV = input id: 'test', message: 'Hello', ok: 'Proceed?', parameters: [choice(choices: 'apple\npear\norange', description: 'Select a fruit for this build', name: 'FRUIT'), string(defaultValue: '', description: '', name: 'myparam')], submitter: 'user1,user2,group1', submitterParameter: 'APPROVER'
echo "This build was approved by: ${approverDEV['APPROVER']}"
}
}
}
stage('Step2'){
steps{
script{
powershell ('''
# Example echo "${approverDEV['APPROVER']}"
# BUT THIS DOESN'T WORK :(
''')
}
}
}
I expect the output is the name of the approver stored in the variable GROOVY approverDEV
Dagett is correct, use double-quotes around the powershell script, then the variables will be evaluated:
script{
powershell ("""
# Example echo "${approverDEV['APPROVER']}"
# BUT THIS DOESN'T WORK :(
""")
}
Using triple double quotes in Groovy is called 'multi-line GString'. In a GString, variables will be evaluated before creating the actual String.
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}"
}