Using Jenkins job parameter in a bat command - jenkins

I'm trying to configure a parameter in Jenkins pipeline and then execute it within bat command:
pipeline {
agent {
label 'master'
}
parameters {
string (
defaultValue: '"someExe.exe"',
description: '',
name : 'varExe'
)
}
stages {
stage("hi") {
steps {
script {
bat '${params.varExe}'
}
}
}
}
}
Unfortunately, i'm getting this error:
'${varExe}'is not recognized as an internal or external command
For some reason, Jenkins doesn't use varExe value.
I've also tried bat '${varExe}' but still no luck.
Any ideas ?

You need to use a double quote here to replace the variable.
bat "${params.varExe}"
You have to be careful with single and double quotes. For the following example, the first one would echo someExe.exe, while the second one would throw a Bad substitution error.
pipeline {
agent any
parameters {
string (
defaultValue: '"someExe.exe"',
description: '',
name : 'varExe')
}
stages {
stage ('Test') {
steps {
script {
sh "echo '${params.varExe}'"
sh 'echo "${params.varExe}"'
}
}
}
}
}

I think for bat command should be like below
bat ''' echo %varExe% '''
reference : pass parameter from jenkins parameterized build to windows batch command

Related

SonarScanner is configured in Jenkins Tools, but '${scannerHome}' is not recognized as an internal or external command

i'm tring to use SonarQube inside my Jenkinsfile
pipeline{
agent any
stages{
stage('build'){
steps{
// invoke command to build with maven
bat 'mvn clean install'
}
}
stage('SonarQube') {
environment {
scannerHome = tool 'SonarQubeScanner'
}
steps {
withSonarQubeEnv('SonarQube') {
bat '${scannerHome}/bin/sonar-scanner.bat'
}
}
}
}
}
this is my SonarQube server
and this is SonarScanner
what is wrong with withSonarQubeEnv step:
withSonarQubeEnv('SonarQube') {
bat '${scannerHome}/bin/sonar-scanner.bat'
}
that I always got an error
'${scannerHome}' is not recognized as an internal or external command,
I see two problems:
you didn't add any installer to SonarQubeScanner tool (only checkbox is checked)
the code is incorrect
Single quotes are not evaluated (treat as is). It means that:
def value = 'ABC'
println '${value}/bin/sonar-scanner.bat'
prints ${value}/bin/sonar-scanner.bat. You have to use double quotes:
def value = 'ABC'
println "${value}/bin/sonar-scanner.bat"
prints ABC/bin/sonar-scanner.bat.
The code should be equal to:
withSonarQubeEnv('SonarQube') {
bat "${scannerHome}/bin/sonar-scanner.bat"
}

Pass a string parameter to Jenkins declarative script

I am declaring a String Parameter in Jenkins -
Name is SLACKTOKEN
Value is qwsaw2345
My Jenkins file has script
pipeline {
agent { label 'trial' }
stages {
stage("Build Docker Image") {
steps{
sh 'docker build -t trial:latest --build-arg SLACK_SIGNING_SECRET=${SLACKTOKEN}'
}
}
}
}
I tried like this, but it didnt work. Could you please let me know how can I pass a value from Jenkins string parameter to Jenkins declarative script file.
I have added the Password parameter in job like below
Inside parameters directive you can provide parameters, details is here.
To pass parameter use params.SLACKTOKEN inside double quotes, not single:
pipeline {
agent { label 'trial' }
parameters {
password(name: 'SLACKTOKEN', defaultValue: '', description: 'Slack Token')
}
stages {
stage("Build Docker Image") {
steps{
sh "docker build -t trial:latest --build-arg SLACK_SIGNING_SECRET=${params.SLACKTOKEN}"
}
}
}
}
Where have you declared your variable?
There are a lot of options:
Example: Use env section from declarative syntax:
pipeline {
agent {
label 'trial'
}
environment {
SLACKTOKEN = 'qwsaw2345'
}
stages {
stage('Build') {
steps {
sh "docker build -t trial:latest --build-arg SLACK_SIGNING_SECRET=${SLACKTOKEN}"
}
}
}
}

Declarative Jenkins Pipeline; How to declare a variable and use it in script or mail notification?

(update below)
I have a declarative pipeline job which can take an argument VERSION.
pipeline {
parameters {
string(name: VERSION, defaultValue: '')
}
// ...
}
If no VERSION is given, like when Gitlab send a hook to this job, I want to compute it from git, so I do something like this
stages {
stage('Prepare') {
steps {
// ...
if (! env.VERSION) {
VERSION = sh(script: "git describe", returnStdout: true).trim()
}
}
}
}
Now I want to "inject" this variable to
my build script. It needs to find "VERSION" in the environment variables
to the jenkins mail notificator. And get it to retreive ${VERSION} in subject or body text
I tried changing above code with
stages {
stage('Prepare') {
steps {
// ...
if (! env.VERSION) {
env.VERSION = sh(script: "git describe", returnStdout: true).trim()
}
}
}
}
Got this error groovy.lang.MissingPropertyException: No such property: VERSION for class: groovy.lang.Binding
I then tried to add a "environment" step below
environment {
VERSION = ${VERSION}
}
but it didn't solve my problem.
I'm looking for any help to solve it.
UPDATE
I now have a working pipeline which looks like
pipeline {
agent any
parameters {
string(name: 'VERSION', defaultValue: '')
}
environment {
def VERSION = "${params.VERSION}"
}
stages {
stage('Prepare & Checkout') {
steps {
script {
if (! env.VERSION) {
VERSION = sh(script: "date", returnStdout: true).trim()
}
echo "** version: ${VERSION} **"
}
}
}
stage('Build') {
steps {
// sh "./build.sh"
echo "** version2: ${VERSION} **"
}
}
} // stages
post {
always {
mail to: 'foo#example.com',
subject: "SUCCESS: ${VERSION}",
body: """<html><body><p>SUCCESS</p></body></html>""",
mimeType: 'text/html',
charset: 'UTF-8'
deleteDir()
}
}
} // pipeline
I needed to add the "environment" step to be able to get $VERSION in all Stages (not only in the one it is manipulated).
I still need to find a way to inject this $VERSION variable in the environment variables, so that my build script can find it.
If you want to inject the variable in the environment so that you can use it later, you could define another variable that is equal to env.VERSION or the output of the shell scrip. Then use that variable in your pipeline eg:
pipeline {
parameters {
string(name: VERSION, defaultValue: '')
}
def version = env.VERSION
stages {
stage('Prepare') {
steps {
// ...
if (!version) {
version = sh(script: "git describe", returnStdout: true).trim()
}
}
}
mail subject: "$version build succeeded", ...
}
If you want other jobs to be able to access the value of VERSION after the build is run, you can write it in a file and archive it.
Edit:
In order for your script to be able to use the version variable, you can either make your script take version as a parameter or you can use the withEnv step.
Assuming you are using Parametrized pipelines, you should call variable as ${params.parameterName}
Although parameters are available in env they currently are created before the first time the pipeline is run, therefore you should access them via params:
In your case:
${params.VERSION}

Split jenkins variable and trigger multiple jobs

I need to clean up some Kubernete namespaces(hello_namespace, second,my_namespace1, my_namespace45,my_namespace44 for example and I do it with a jenkins job.
I read with kubectl the namespace I need to clean up and then I want to fire a job to delete it, My code should be something like that
pipeline {
agent { label 'master' }
stages {
stage('Clean e2e') {
steps {
script {
sh "kubectl get namespace |egrep 'my_namespace[0-9]+'|cut -f1 -d ' '>result.txt"
def output=readFile('result.txt').trim()
}
}
}
The ouput of this code will be the variable $output with the values:
my_namespace1
my_namespace45
my_namespace44
Separated by line, now I want to fire a job with the namespace like parameter , how can I do that? (My problem is to read the file and fire independent job for each namespace)
while (output.nextLine() callJob)
The job call should be like
build job: 'Delete temp Stage', parameters:
[string(name: 'Stage', value: "${env.stage_name}")]
I already got it :)
#!groovy
pipeline {
agent { label 'master' }
stages {
stage('Clean up stages') {
steps {
script {
sh '(kubectl get namespace |egrep "namespace[0-9]+"|cut -f1 -d " "|while read i;do echo -n $i";" ; done;)>result.txt'
def stages = readFile('result.txt').trim().split(';')
for (stage in stages) {
if (stage?.trim()) {
echo "deleting stage: $stage"
build job: 'Delete temp Stage', parameters:
[string(name: 'Stage', value: "$stage")]
}
}
}
}
}
}
}

Cannot define variable in pipeline stage

I'm trying to create a declarative Jenkins pipeline script but having issues with simple variable declaration.
Here is my script:
pipeline {
agent none
stages {
stage("first") {
def foo = "foo" // fails with "WorkflowScript: 5: Expected a step # line 5, column 13."
sh "echo ${foo}"
}
}
}
However, I get this error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 5: Expected a step # line 5, column 13.
def foo = "foo"
^
I'm on Jenkins 2.7.4 and Pipeline 2.4.
The Declarative model for Jenkins Pipelines has a restricted subset of syntax that it allows in the stage blocks - see the syntax guide for more info. You can bypass that restriction by wrapping your steps in a script { ... } block, but as a result, you'll lose validation of syntax, parameters, etc within the script block.
I think error is not coming from the specified line but from the first 3 lines. Try this instead :
node {
stage("first") {
def foo = "foo"
sh "echo ${foo}"
}
}
I think you had some extra lines that are not valid...
From declaractive pipeline model documentation, it seems that you have to use an environment declaration block to declare your variables, e.g.:
pipeline {
environment {
FOO = "foo"
}
agent none
stages {
stage("first") {
sh "echo ${FOO}"
}
}
}
Agree with #Pom12, #abayer. To complete the answer you need to add script block
Try something like this:
pipeline {
agent any
environment {
ENV_NAME = "${env.BRANCH_NAME}"
}
// ----------------
stages {
stage('Build Container') {
steps {
echo 'Building Container..'
script {
if (ENVIRONMENT_NAME == 'development') {
ENV_NAME = 'Development'
} else if (ENVIRONMENT_NAME == 'release') {
ENV_NAME = 'Production'
}
}
echo 'Building Branch: ' + env.BRANCH_NAME
echo 'Build Number: ' + env.BUILD_NUMBER
echo 'Building Environment: ' + ENV_NAME
echo "Running your service with environemnt ${ENV_NAME} now"
}
}
}
}
In Jenkins 2.138.3 there are two different types of pipelines.
Declarative and Scripted pipelines.
"Declarative pipelines is a new extension of the pipeline DSL (it is basically a pipeline script with only one step, a pipeline step with arguments (called directives), these directives should follow a specific syntax. The point of this new format is that it is more strict and therefore should be easier for those new to pipelines, allow for graphical editing and much more.
scripted pipelines is the fallback for advanced requirements."
jenkins pipeline: agent vs node?
Here is an example of using environment and global variables in a Declarative Pipeline. From what I can tell enviroment are static after they are set.
def browser = 'Unknown'
pipeline {
agent any
environment {
//Use Pipeline Utility Steps plugin to read information from pom.xml into env variables
IMAGE = readMavenPom().getArtifactId()
VERSION = readMavenPom().getVersion()
}
stages {
stage('Example') {
steps {
script {
browser = sh(returnStdout: true, script: 'echo Chrome')
}
}
}
stage('SNAPSHOT') {
when {
expression {
return !env.JOB_NAME.equals("PROD") && !env.VERSION.contains("RELEASE")
}
}
steps {
echo "SNAPSHOT"
echo "${browser}"
}
}
stage('RELEASE') {
when {
expression {
return !env.JOB_NAME.equals("TEST") && !env.VERSION.contains("RELEASE")
}
}
steps {
echo "RELEASE"
echo "${browser}"
}
}
}//end of stages
}//end of pipeline
You are using a Declarative Pipeline which requires a script-step to execute Groovy code. This is a huge difference compared to the Scripted Pipeline where this is not necessary.
The official documentation says the following:
The script step takes a block of Scripted Pipeline and executes that
in the Declarative Pipeline.
pipeline {
agent none
stages {
stage("first") {
script {
def foo = "foo"
sh "echo ${foo}"
}
}
}
}
you can define the variable global , but when using this variable must to write in script block .
def foo="foo"
pipeline {
agent none
stages {
stage("first") {
script{
sh "echo ${foo}"
}
}
}
}
Try this declarative pipeline, its working
pipeline {
agent any
stages {
stage("first") {
steps{
script {
def foo = "foo"
sh "echo ${foo}"
}
}
}
}
}

Resources