How to set an environment variable from Jenkinsfile - jenkins

How can I set a new environment variable from within a Jenkinsfile using declarative pipeline?
I know that I can read environment variables using env like this one for example ${env.JOB_NAME}.
But how can I set a new environment variable which can be be used by my build script for example. I want to do something like below. Is this the correct way?
stage("build_my_code") {
steps {
sh 'MY_ENV_VAR="some_value"'
sh './my_script.sh $MY_ENV_VAR'
}
}

You can use script step to run Groovy script in declarative pipeline,
Then in script step to set environment by env.xxx=yyy
stage("build_my_code") {
steps {
script {
// the MY_ENV_VAR environment variable should not exist,
// not allow to overwrite value of an existing environment variable.
env.MY_ENV_VAR="some_value"
}
sh './my_script.sh $MY_ENV_VAR'
}
}

Related

How to pass user defined variables file in Jmeter through Jenkins

I need to execute the same jmx file for two different environments. The user-defined variable for both is different. How to pass user-defined variables through Jenkins to overcome that.
In Jemeter you should be able to read properties either from Environment variables, System variables or property files. You can refer this for reading from environment variables.
Then in Jenkins you can set the environment variables before executing your Jmeter script. There are many ways to do this in Jenkins. Following is a multi-stage example.
stage('Dev Testing') {
steps {
script {
sh '''
TEST_HOST="http://dev.com"
{JMETER EXEcution}
'''
}
}
}
stage('QA Testing') {
steps {
script {
sh '''
TEST_HOST="http://qa.com"
{JMETER EXEcution}
'''
}
}
}
Other Options
Also as I mentioned you can use System properties or property files with Jemter scripts. This is a good tutorial for this. Once you set this up in the Jmeter script you can either generate the property file from Jenkins or use an appropriate property file based on the environment. Or you can pass the properties directly to the Jemeter script as shown below.
jmeter -Jgroup1.threads=7 -Jhostname1=www.realhost.edu

How to inject environment variables from Groovy script in Jenkins piplenine

I need to migrate the freestyle project to the Jenkins pipeline. Any idea how to implement environment variable injection with groovy script to declarative pipeline?
I need pipeline code for this:
you can try add your groovy script into environment
environment {
if() {
env.xxx=yyy // xxx is the name of environment variable
}
}

Set environments from sh file in jenkins and keep it for the rest of the build

In my pipeline, I would like to source a file, setting environment variables like . ./file.sh and keep them set for the rest of the pipeline.
I think this is not implemented given there's an issue opened for some years already https://issues.jenkins-ci.org/browse/JENKINS-10773
At the moment, I tested doing:
stage("Stage") {
steps {
sh ". ./file.sh && env"
sh "env"
}
}
The 2 env output different values. I expect Jenkins to create a new shell every time. Is there an option to not invoke a new shell?.
With what I know, I see 3 possibilities:
Execute all my commands in one sh statement or wrap the execution in a script. The problem is that it makes debugging quite hard.
Source the file at each sh command.
Create a custom groovy function wrapping the call.
The 2 last solutions sound dirty, any suggestion is welcome.
Looks like we can follow environment directive feature to handle both global variable and also stage specific variables.
So in your instance if you define all variables from file.sh within Global scope, then printing will give desired result.
pipeline {
agent any
environment {
myGlobVar = '2020'
}
stages {
stage('Example') {
environment {
myStgeSpecificVar = 2020.2
}
steps {
sh 'printenv'
}
}
}
}

Setting Environment Variables at the User level

I have a Jenkins setup where i want to configure the environment variable before building my pipeline.
I can set the environment variable in the configure page and use it in Jobs. However, I can not give the Administrator permission to the user to set it up. In-order to set the Environment variable user should have the admin access.
I have taken a look into the Injecting Environment variable at the Job level by installing Environment inject plugin. In this case also, user has to come to the configuring the job and set up.
Please let me know if there is a way to have the external script file and set the environment variable through it.
You can use the "This project is parameterized" option in jenkins job configure page and pass the arguments.
You can also have "environment" block in Jenkinsfile to declare all the variable.
environment {
CC = 'clang'
}
Please follow the link for more information.
please refer https://jenkins.io/doc/book/pipeline/syntax/#environment
pipeline {
agent none
environment {
field = 'some'
}
stages {
stage ('Preparation') {
agent { label 'master'}
environment {
JENKINS_PATH = sh(script: 'pwd', , returnStdout: true).trim()
}
steps {
echo "Hello world"
echo "PATH=${JENKINS_PATH}"
sh 'echo "JP=$JENKINS_PATH"'
}
}
}
}

In jenkins declarative pipeline, how can I set environment variable based on method?

In jenkins declarative pipeline, how can I set the value of an environment variable based on custom groovy/powershell method? For instance, if I have a delcarative pipeline as follows, can I use a shared library method to set this value?
Essentially I am trying to use a multibranch Declarative Pipeline jenkins job which has a deploy stage, but I need to ensure that develop branches are deployed to DEV, Release branches are deploying to STG, but using the same pipeline. My thought was to create an environment variable that is set based on a custom method (in perhaps Groovy in shared library), and that method would simply look at the current value for env.BRANCH and simply have a little logic to set the value of the target deploy environment. Here is an example of what I envision
pipeline {
environment {
DEPLOY_ENV = mapBranchToDeployEnvironment(${BRANCH})
}
And then in my deploy stage I would use this value in two powershell invocations
bat "powershell .\\Deploy-Service -Environment ${DEPLOY_ENV}"
bat "powershell .\\Deploy-ServiceProxy -Environment ${DEPLOY_ENV}"
Otherwise, How are people current solving the problem of using the same pipeline to deploy to different environments while using the variables across many other function invocations? What is the recommended approach from Jenkins on mapping a branch name that triggered the build to an environment (if any) it should be deployed to?
Based on my understanding, the Declarative Pipeline allows a pipeline to be "multibranch", which, if the job deploys as well, it needs to map to an deploy environment. How else would a pipeline deploy using multibranch to multiple environments when all the global jenkins pipeline environment variables are the same value for every job /branch execution?
In the above scenario, the pipeline variable 'DEPLOY_ENV' is derived from other environment variables that are set by the job and are available typically at the stage level, but here we are looking to set the value globally so that we can use it across stages
Update: My issue was that I didnt realize how simple it was and instead thought that I had to pass in a stage or script object into a groovy shared library function, when in fact its as simple as creating a shared library, then directly referencing the environment variables in the method. Easy. Thank you.
I had exactly the same problem, and indeed it is possible to use a shared library method. But there is another solution, more simple if you do not have a shared library set-up yet, that consists in defining a groovy method before the Pipeline statement and then use it inside your pipeline like this :
def getEnvFromBranch(branch) {
if (branch == 'master') {
return 'production'
} else {
return 'staging'
}
}
pipeline {
agent any
environment {
targetedEnv = getEnvFromBranch(env.BRANCH_NAME)
}
stages {
stage('Build') {
steps {
echo "Building in ${env.targetedEnv}"
}
}
}
}
You can do exactly what you're suggesting. You should create a jenkins shared library with a var (a new DSL method). These can be called to assign to a pipeline-wide environment variable. You had it basically correct. Here's a Jenkinsfile fragment to assign to an environment variable:
environment {
DEPLOY_ENV = mapBranchToDeployEnvironment()
}
You don't need to pass the branch to the mapBranchToDeployEnvironment DSL method, since you can access the branch in that method. sample contents of vars/mapBranchToDeployEnvironment.groovy in shared library look like this:
def call() {
echo "branch is: ${env.BRANCH_NAME}"
if (env.BRANCH_NAME == 'master') {
return 'prod'
} else {
return 'staging'
}
}
You probably shouldn't expect this to be a five minute task, but you'll get it. Good luck!
stage('Prepare env variables') {
steps {
script {
if (env.BRANCH_NAME == 'master') {
echo 'Copying project-stg.env file...';
sh 'cp /opt/project-stg.env .env';
} else {
echo 'Copying project-dev.env file...';
sh 'cp /opt/project-dev.env .env';
}
}
}
}

Resources