I want to set dynamic variable in Jenkinsfile
and below is my Jenkinsfile
def determineProjectByBranch(branchName) {
String projectName = "";
if (branchName.contains("api")) {
projectName = "api";
} else if (branchName.contains("auth")) {
projectName = "auth";
}
return projectName;
}
pipeline {
agent any
stages {
stage("Build") {
environment {
PROJECT_NAME = determineProjectByBranch("${GIT_BRANCH}")
}
steps {
script {
PROJECT_NAME = determineProjectByBranch("${GIT_BRANCH}")
}
echo "branch name: ${GIT_BRANCH}"
echo "project name: " PROJECT_NAME // it shows empty value
echo "project name: ${PROJECT_NAME}"
sh "chmod x gradlew"
sh "./gradlew ${PROJECT_NAME}:clean ${PROJECT_NAME}:build"
}
}
}
}
As you can see the above code i want to use function so that it can set the dynamic value but i can't find the right way to set variable dynamically.
I also tried the below code but it didn't work either.
def determineProjectByBranch(branchName) {
String projectName = "";
if (branchName.contains("api")) {
projectName = "api";
} else if (branchName.contains("auth")) {
projectName = "auth";
}
return projectName;
}
def projectName
pipeline {
agent any
stages {
stage("Build") {
steps {
script {
projectName = determineProjectByBranch("${GIT_BRANCH}")
}
echo "branch name: ${GIT_BRANCH}"
echo "project name: " projectName // it shows empty value
echo "project name: ${projectName}"
sh "chmod x gradlew"
sh "./gradlew ${projectName}:clean ${projectName}:build"
}
}
}
}
You may think the function returns empty value but when i build with below code it shows expected value
def determineProjectByBranch(branchName) {
String projectName = "";
if (branchName.contains("api")) {
projectName = "api";
} else if (branchName.contains("auth")) {
projectName = "auth";
}
return projectName;
}
def projectName
pipeline {
agent any
stages {
stage("Build") {
steps {
echo "branch name: ${GIT_BRANCH}"
echo "project name: " determineProjectByBranch("${GIT_BRANCH}") // it shows expected value
echo "project name: ${projectName}"
sh "chmod x gradlew"
sh "./gradlew ${PROJECT_NAME}:clean ${PROJECT_NAME}:build"
}
}
}
}
I'm not sure define variable depends on Jenkins version but mine is 2.361.2. Any help would be appreciate thank you in advance