I am new to Jenkins and am confused between variables. I have tried to write a Jenkinsfile where I am simply using an If condition to deploy a file. Following is the file:
def checker = "Trial"
pipeline{
agent any
stages{
stage('Stage 1'){
steps{
script{
checker = sh(returnStdout: true, script: 'echo "Trial" ')
if (checker == 'Trial'){ echo "Hello"}
else {echo "Hi"}
}
}
}
}
}
The output should ideally be "Hello", however I get "Hi" always. How do I get the If condition working?? Thanks
You missed the trim() to remove the newline at the end of output of the bash.
checker = sh(returnStdout: true, script: 'echo "Trial" ').trim()
Related
My jenkinsfile containes two stages, build and upload&scan (veracode for static scans). My console output would contain somthing like: build_id="21682834" refers to veracode scan ID.
Can anyone help in finding this number and set it as environment variable?
Check the following code.
def consoleLog = Jenkins.getInstance().getItemByFullName(env.JOB_NAME).getBuildByNumber(Integer.parseInt(env.BUILD_NUMBER)).logFile.text
def buildId = (consoleLog =~ 'build_id="(.*)"')[0][1]
echo "build_id: $buildId"
env.build_id = buildId
Full Pipeline for testing.
pipeline {
agent any
stages {
stage('Hello') {
steps {
script {
echo "Something"
echo "Something"
echo "Something"
echo "Something"
echo 'build_id="21682834"'
echo "Something"
echo "Something"
def consoleLog = Jenkins.getInstance().getItemByFullName(env.JOB_NAME).getBuildByNumber(Integer.parseInt(env.BUILD_NUMBER)).logFile.text
def buildId = (consoleLog =~ 'build_id="(.*)"')[0][1]
echo "build_id: $buildId"
env.build_id = buildId
}
}
}
}
}
can i know which part i am doing wrong. The file not in server but however, every time i execute it goes to true statement
pipeline {
agent any
stages{
stage('Test') {
steps{
script{
hasWar = sh(returnStdout: true, script: 'sshpass -p ${password} ssh ${username}#123.12.32.33 \'if [ -f /home/nityo/warFile1.war ]; then echo true; else echo false; fi\'')
if (hasWar) {
echo 'Has war'
} else {
echo 'No war files'
}
}
}
}
}
}
Assuming the script part echos true or false to the console in the expected conditions, there is one more thing you didn't take into account. In Groovy, every non-empty string evaluates to true when used in the context of the boolean variable. It's called Groovy Truth.
If you want to evaluate string value false to an appropriate boolean value, you have to use toBoolean() method that returns false if the string value stores false literal, and true if it stores true literal.
https://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/String.html#toBoolean()
Also, consider adding trim() to the sh() step so all whitespaces are trimmed from the output when you store it under the hasWar variable.
pipeline {
agent any
stages{
stage('Test') {
steps{
script{
hasWar = sh(returnStdout: true, script: 'sshpass -p ${password} ssh ${username}#123.12.32.33 \'if [ -f /home/nityo/warFile1.war ]; then echo true; else echo false; fi\'').trim()
if (hasWar.toBoolean()) {
echo 'Has war'
} else {
echo 'No war files'
}
}
}
}
}
}
I am facing some issues in jenkins environment section while executing the jenkins pipeline environment section.
import groovy.transform.Field
#Field gitScriptPath = "https://raw.github.com/Innovation/"
#Field clrInfo
#Field gitlabMem
#Field gitSubGroupURL
#Field clrDuration
#Field cloudProvider
#Field userSpecData
#Field slackIntMes
pipeline {
agent { label 'master' }
environment {
GITHUB_TOKEN = credentials(' GITHUB_TOKEN')
GIT_URL = 'github.com/Innovation/exp-selling-iac.git'
PRE_PROV = 'k8s-jobs/iac_preprovision.yaml'
OS_PROV = 'k8s-jobs/iac_openshift.yaml'
USER_PROV = 'k8s-jobs/rhos-user-onboard-offboard.yaml'
ISTIO_PROV = 'k8s-jobs/iac_istio.yaml'
KAFKA_PROV = 'k8s-jobs/iac_kafka.yaml'
MONOLITH_PROV = 'k8s-jobs/iac_monolith.yaml'
POST_PROV = 'k8s-jobs/iac_postprovision.yaml'
DEVOPS_PROV = 'k8s-jobs/k8s_iac_devops.yaml'
dummy = sh ( script: '''echo "${USER_SPEC}" > userspec.yaml''', returnStdout: true )
NAMESPACE = sh ( script: "$JENKINS_HOME/custompath/yq r userspec.yaml Cluster.Name", returnStdout: true )
requestor = sh ( script: "$JENKINS_HOME/custompath/yq r userspec.yaml Cluster.Users.User1.ID", returnStdout: true ).trim()
APPOPS_ROLE = 'appops-customrole-v2'
}
stages {
stage('Download - Groovy Scripts'){
Here we need to get the value of NAMESPACE and requestor after executing the dummy.
But the line starting with dummy is happening after NAMESPACE and requestor lines.
The same quote was working earlier. IF i remove requestor = or APPOPS_ROLE = then everything will be fine. Please help to understand what is happening here.
As i work around i can make APPOPS_ROLE as a parameter in jenkins by configuring the job. This has something to do with the case of the variable also. ie if i make dummy ---> DUMMY it will make a difference.
Jenkins ver. 2.204.2 on openshift 3.11
I don't know why the ordering is undefined. Maybe the assignments are first stored in a hash table and then the hash table is enumerated, which would result in a seemingly random order.
As a workaround you could move the environment initialization into a stage, where you could use a script block to ensure execution order:
pipeline {
agent { label 'master' }
stages {
stage('Initialize') {
steps {
script {
env.dummy = sh ( script: '''echo "${USER_SPEC}" > userspec.yaml''', returnStdout: true )
env.NAMESPACE = sh ( script: "$JENKINS_HOME/custompath/yq r userspec.yaml Cluster.Name", returnStdout: true )
env.requestor = sh ( script: "$JENKINS_HOME/custompath/yq r userspec.yaml Cluster.Users.User1.ID", returnStdout: true ).trim()
...
}
}
}
stage('Download - Groovy Scripts'){
...
}
}
}
So, I can capture a variable in a step like this:
stage('blah') {
script {
INVENTORY_FILE = sh(returnStdout: true, script: 'echo $(date +%Y%m%d).yml')
}
}
And this works. Except I need this variable to be in scope for the entire Jenkinsfile, for all stages, not just this one. But I can't seem to use sh() outside of a stage. Any ideas?
You can define a variable at the top of Jenkinsfile, then you can access this variable in entire Jenkinsfile.
def INVENTORY_FILE
pipeline {
stages {
stage('blah') {
script {
INVENTORY_FILE = sh(returnStdout: true, script: 'echo $(date +%Y%m%d).yml').trim()
}
}
}
}
I am trying to write a jenkins build script for my project in Groovy.
the problem is that I want to define some variables at the top of the script and use them when I want as Environment variable.
def someVariable = 'foo'
pipeline{
agent any
stages{
stage("build"){
environment {
specialParameter = someVariable
}
steps{
...
}
}
...
}
}
I have some other steps that their environment variables are different and also I want to just change the top of the script to able to build other branches and so on. so I just want a way to use the defined someVariable in the environment body.
Thanks
First you can just use the environment section to define environment variables which are known in you whole script:
pipeline {
agent any
environment {
TEST='myvalue'
}
stages{
stage("build"){
steps{
...
}
}
}
}
You can also define a variable which is only known in one stage:
pipeline {
agent any
stages{
stage("build"){
environment {
TEST='myvalue'
}
steps{
...
}
}
}
}
But for your solution (using def above the pipeline) you can just do:
def someVariable = 'foo'
pipeline{
agent any
stages{
stage("build"){
steps{
echo someVariable
}
}
}
}
This will output 'foo'.
You can get more informations on variable declarations syntax by reading Jenkins online book.
UPDATE:
def someVariable = 'foo'
pipeline{
agent any
stages{
stage("build"){
environment {
TEST = sh(script: "echo -n ${someVariable}", returnStdout: true)
}
steps{
sh 'echo "${TEST}"'
}
}
}
}
Output:
[test] Running shell script
+ echo foo
foo
Just found another way to use defined environment variables.
def getsomeVariable (){
return 'foo'
}
pipeline{
agent any
stages{
stage("build"){
environment {
specialParameter = getsomeVariable()
}
steps{
...
}
}
...
}
}