How to pass groovy variable to powershell in Jenkins pipeline? - jenkins

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.

Related

Jenkins Publish Over SSh pipeline parameterized

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.

Create environment variable from parameters in Jenkins

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.

Need to get user email id as input and send logs in jenkins

I have a shell script wil runs on taking user inputs and send logs to users when fails syntax I use: ./script.sh env usecase emailid
Now am doing a jenkins build and not sure on how to get user input for email id . I am currently getting 2 inputs using choice parameter.
I want user to give email id and its passed as a parameter .
#Library('Shared#release/v1')
import jenkins.BuildSupport
properties([parameters([choice(choices: ['dev''uat', 'prod'], description: 'Select the Environment', name: 'ENVIRONMENT'), choice(choices: ['a1','a2','all'], description: 'Select the Service', name: 'SERVICENAME')])])
node{
WORKSPACE = pwd()
//checkout code from shared library
stage ('Code Checkout'){
codeCheckout
}
//post build work
stage('Executing Health Check') {
withEnv(["WORKSPACE=${WORKSPACE}","ENVIRONMENT=${params.ENVIRONMENT}","SERVICENAME=${params.SERVICENAME}",]) {
sh '''
set +x
ls -l
./script.sh ${ENVIRONMENT} ${SERVICENAME}
'''
}
}
}
I need the script.sh to take 3rd parameter which will be the email id entered by user
So couple of things going on here. First, you need to add a string parameter to ask the user for input, then you need to pass that to the shell script, and then you need to make sure the shell script can use it.
I don't see the need for withEnv, you can pass variables to a script without that.
Just make sure your shell script is getting the EMAIL_ADDRESS from $3
#!groovy
#Library('Shared#release/v1')
import jenkins.BuildSupport
properties([parameters([string(name: 'EMAIL_ADDRESS', description: 'Enter the email address'), choice(choices: ['dev','uat','prod'], description: 'Select the Environment', name: 'ENVIRONMENT'), choice(choices: ['a1','a2','all'], description: 'Select the Service', name: 'SERVICENAME')])])
node{
WORKSPACE = pwd()
//checkout code from shared library
stage ('Code Checkout'){
codeCheckout
}
//post build work
stage('Executing Health Check') {
sh '''
set +x
ls -l
./script.sh $ENVIRONMENT $SERVICENAME $EMAIL_ADDRESS
'''
}
}
Example of sending email from Jenkins scripted pipeline/ Groovy
stage('Email the results') {
emailext attachLog: true,
attachmentsPattern: '*',
to: "${EMAIL_ADDRESS}",
subject: "${currentBuild.currentResult} - ${ENVIRONMENT} ${SERVICE}",
body: """
Blah blah blah
"""
}

Not able to fetch parameters in Jenkins Pipeline script

I am trying to execute a .vbs file by passing parameters in Jenkins pipeline script.
After clicking "Build with Parameters" I entered all input parameters but below script is not passing the values I entered.
The '${param.XXX}' seems to be not working. The values passed to vbs are always ${params.DELIVERY} ${params.SOURCE_ENV} ${params.TERGET_ENV} ${params.GENREPORT}
but ideally arguments passed to vbs should be equal to the data entered before triggering pipeline. Can anyone please help me?
#!/usr/bin/env groovy
pipeline {
agent any
parameters {
string(defaultValue: '', description: 'Delivery name', name: 'DELIVERY')
choice(choices:'DEV1\nDEV2\nDEV3',description: 'Select Source environment', name: 'SOURCE_ENV')
choice(choices:'TEST1\nTEST2\nTEST3',description: 'Select target environment', name: 'TERGET_ENV')
choice(choices:'Yes\nNo',description: 'Generate Report?', name: 'GENREPORT')
}
stages {
stage("Start Batch") {
steps {
bat '''
echo '${params.DELIVERY}'
echo '${params.SOURCE_ENV}'
echo '${params.TERGET_ENV}'
echo '${params.GENREPORT}'
cd "C:\\Users\\DELIVERY_BATCH\\src"
cscript.exe DELEXCEBATCH.vbs "C:\\Users\\Documents\\BatchFiles" ${params.DELIVERY} ${params.SOURCE_ENV} ${params.TERGET_ENV} ${params.GENREPORT}
EXIT /B 0
'''
}
}
stage("Create Summary Excel sheet") {
steps {
bat '''
echo 'Batch Execution is successful'
'''
}
}
}
}
This:
bat '''
Should be:
bat """
Because variables are only evaluated when double quotes are used.

How to access parameters in a Parameterized Build?

How do you access parameters set in the "This build is parameterized" section of a "Workflow" Jenkins job?
TEST CASE
Create a WORKFLOW job.
Enable "This build is parameterized".
Add a STRING PARAMETER foo with default value bar text.
Add the code below to Workflow Script:
node()
{
print "DEBUG: parameter foo = ${env.foo}"
}
Run job.
RESULT
DEBUG: parameter foo = null
I think the variable is available directly, rather than through env, when using Workflow plugin.
Try:
node()
{
print "DEBUG: parameter foo = ${foo}"
}
I tried a few of the solutions from this thread. It seemed to work, but my values were always true and I also encountered the following issue:
JENKINS-40235
I managed to use parameters in groovy jenkinsfile using the following syntax: params.myVariable
Here's a working example:
Solution
print 'DEBUG: parameter isFoo = ' + params.isFoo
print "DEBUG: parameter isFoo = ${params.isFoo}"
A more detailed (and working) example:
node() {
// adds job parameters within jenkinsfile
properties([
parameters([
booleanParam(
defaultValue: false,
description: 'isFoo should be false',
name: 'isFoo'
),
booleanParam(
defaultValue: true,
description: 'isBar should be true',
name: 'isBar'
),
])
])
// test the false value
print 'DEBUG: parameter isFoo = ' + params.isFoo
print "DEBUG: parameter isFoo = ${params.isFoo}"
sh "echo sh isFoo is ${params.isFoo}"
if (params.isFoo) { print "THIS SHOULD NOT DISPLAY" }
// test the true value
print 'DEBUG: parameter isBar = ' + params.isBar
print "DEBUG: parameter isBar = ${params.isBar}"
sh "echo sh isBar is ${params.isBar}"
if (params.isBar) { print "this should display" }
}
Output
[Pipeline] {
[Pipeline] properties
WARNING: The properties step will remove all JobPropertys currently configured in this job, either from the UI or from an earlier properties step.
This includes configuration for discarding old builds, parameters, concurrent builds and build triggers.
WARNING: Removing existing job property 'This project is parameterized'
WARNING: Removing existing job property 'Build triggers'
[Pipeline] echo
DEBUG: parameter isFoo = false
[Pipeline] echo
DEBUG: parameter isFoo = false
[Pipeline] sh
[wegotrade-test-job] Running shell script
+ echo sh isFoo is false
sh isFoo is false
[Pipeline] echo
DEBUG: parameter isBar = true
[Pipeline] echo
DEBUG: parameter isBar = true
[Pipeline] sh
[wegotrade-test-job] Running shell script
+ echo sh isBar is true
sh isBar is true
[Pipeline] echo
this should display
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
I sent a Pull Request to update the misleading pipeline tutorial#build-parameters quote that says "they are accessible as Groovy variables of the same name.". ;)
Edit: As Jesse Glick pointed out:
Release notes go into more details
You should also update the Pipeline Job Plugin to 2.7 or later, so that build parameters are defined as environment variables and thus accessible as if they were global Groovy variables.
When you add a build parameter, foo,
it gets converted to something which acts like a "bare variable",
so in your script you would do:
node {
echo foo
}
If you look at the implementation of the workflow script, you will see that when a script is executed, a class called WorkflowScript is
dynamically generated. All statements in the script are executed in the context of this class. All build parameters passed down to this script are converted to properties which are accessible from this class.
For example, you can do:
node {
getProperty("foo")
}
If you are curious, here is a workflow script I wrote which attempts to print out the build parameters, environment variables, and methods on the WorkflowScript class.
node {
echo "I am a "+getClass().getName()
echo "PARAMETERS"
echo "=========="
echo getBinding().getVariables().getClass().getName()
def myvariables = getBinding().getVariables()
for (v in myvariables) {
echo "${v} " + myvariables.get(v)
}
echo STRING_PARAM1.getClass().getName()
echo "METHODS"
echo "======="
def methods = getMetaClass().getMethods()
for (method in methods) {
echo method.getName()
}
echo "PROPERTIES"
echo "=========="
properties.each{ k, v ->
println "${k} ${v}"
}
echo properties
echo properties["class"].getName()
echo "ENVIRONMENT VARIABLES"
echo "======================"
echo "env is " + env.getClass().getName()
def envvars = env.getEnvironment()
envvars.each{ k, v ->
println "${k} ${v}"
}
}
Here is another code example I tried, where I wanted to test to see
if a build parameter was set or not.
node {
groovy.lang.Binding myBinding = getBinding()
boolean mybool = myBinding.hasVariable("STRING_PARAM1")
echo mybool.toString()
if (mybool) {
echo STRING_PARAM1
echo getProperty("STRING_PARAM1")
} else {
echo "STRING_PARAM1 is not defined"
}
mybool = myBinding.hasVariable("DID_NOT_DEFINE_THIS")
if (mybool) {
echo DID_NOT_DEFINE_THIS
echo getProperty("DID_NOT_DEFINE_THIS")
} else {
echo "DID_NOT_DEFINE_THIS is not defined"
}
}
Use double quotes instead of single quotes
e.g. echo "$foo" as opposed to echo '$foo'
If you configured your pipeline to accept parameters using the Build with Parameters option, those parameters are accessible as Groovy variables of the same name. See Here.
You can drop the semicolon (;), drop the parentheses (( and )), and use single quotes (') instead of double (") if you do not need to perform variable substitutions. See Here. This clued me into my problem, though I've found that only the double (") is required to make it work.
To parameter variable add prefix "params."
For example:
params.myParam
Don't forget: if you use some method of myParam, may be you should approve it in "Script approval".
You can also try using parameters directive for making your build parameterized and accessing parameters:
Doc:
Pipeline syntax: Parameters
Example:
pipeline{
agent { node { label 'test' } }
options { skipDefaultCheckout() }
parameters {
string(name: 'suiteFile', defaultValue: '', description: 'Suite File')
}
stages{
stage('Initialize'){
steps{
echo "${params.suiteFile}"
}
}
}
Hope the following piece of code works for you:
def item = hudson.model.Hudson.instance.getItem('MyJob')
def value = item.lastBuild.getEnvironment(null).get('foo')
The following snippet gives you access to all Job params
def myparams = currentBuild.rawBuild.getAction(ParametersAction)
for( p in myparams ) {
pMap[p.name.toString()] = p.value.toString()
}
Please note, the way that build parameters are accessed inside pipeline scripts (pipeline plugin) has changed. This approach:
getBinding().hasVariable("MY_PARAM")
Is not working anymore. Please try this instead:
def myBool = env.getEnvironment().containsKey("MY_BOOL") ? Boolean.parseBoolean("$env.MY_BOOL") : false
As per Pipeline plugin tutorial:
If you have configured your pipeline to accept parameters when it is built — Build with Parameters — they are accessible as Groovy variables of the same name.
So try to access the variable directly, e.g.:
node()
{
print "DEBUG: parameter foo = " + foo
print "DEBUG: parameter bar = ${bar}"
}

Resources