Issue
Im trying to use a variable created in a bash ("nombre" variable) and use it in a to trigger to another job with this parameter, as you can see i tried with "env.nombre":
stages{
stage('PART1'){
steps{
cleanWs()
git credentialsId: 'ssh-git-access', url: '[email protected]:XXXX/XXXXX.git'
script {
sh '''
nombre=$(cat /home/user/nombre.txt)
echo $nombre
'''
///THIS ECHO PRINT "HELLO"
}
}
}
stage('PART2'){
steps{
//ERROR HERE
echo env.nombre
build job: 'JOB_2', parameters: [string(name: 'nombre', value: env.nombre)]
}
}
}
}
I also tried with this:
environment {
TRABAJO_NAME=env.nombre
}
Solution
I will answer me.
When i use sh directive, a new instance of shell (most likely bash) is created. As usual Unix processes, it inherits the environment variables of the parent. When my script sets an environment variable, the environment of bash is updated. Once your script ends, the bash process that ran the script is destroyed, and all its environment is destroyed with it.
def script_output = sh(returnStdout: true, script: '''
#!/bin/bash
nombre=$(cat /home/user/nombre.txt)
echo $nombre
''')
script_output = script_output.trim()
VAR_NAME = script_output
//USING VARIABLE IN 'bash enviroment'
echo "VAR_NAME is ${VAR_NAME}"
//USING VARIABLE IN 'jenkins enviroment'
echo VAR_NAME
I dont know if its a optimal way to do it. Let me know if someone have another way.
Answered By - FrankieGG
Answer Checked By - David Marino (JavaFixing Volunteer)