In Jenkins, I’ve created a pipeline to go through several stages. In the second stage, after cloning the repository in the first stage, I want to check if a file called ${FILENAME}
exists in the ${REPOSITORY_NAME}/apps
directory.
If it exists, I want to perform kubectl rollout restart deployment ${APPLICATION_NAME}
, and if it does not exist, I want to create such application.
I am not used to Jenkins’ environment variables, and having trouble using it for the condition in the if-else statement.
Even when the ${FILENAME}
exists, env.ALREADY_EXISTS
won’t change to "true"
; however I’ve confirmed that echo "ALREADY_EXISTS = ${ALREADY_EXISTS}"
results in ALREADY_EXISTS = true
.
Why is env.ALREADY_EXISTS
not updated and how can I fix this? Thanks in advance.
pipeline {
agent any
environment {
APPLICATION_NAME="myapp"
REPOSITORY_NAME="myrepo"
FILENAME="${APPLICATION_NAME}-app.yaml"
ALREADY_EXISTS="false"
}
stages {
stage("Clone Git Repository") {
steps {
git(
url: "https://github.com/myid/${REPOSITORY_NAME}.git",
branch: "main",
changelog: true,
credentialsId: 'mycreds',
poll: true
)
}
}
stage("Check if file already exists") {
steps {
sh '''
cd ./apps
if [ -f "${FILENAME}" ]; then
echo "${FILENAME} exists"
ALREADY_EXISTS="true"
else
echo "${FILENAME} does not exist"
ALREADY_EXISTS="false"
fi
echo "ALREADY_EXISTS = ${ALREADY_EXISTS}"
cd ..
'''
}
}
stage("Rollout or create app") {
steps {
script {
if (env.ALREADY_EXISTS == "true") {
withKubeConfig([namespace: "${APPLICATION_NAME}-${CLIENT_ID}"]) {
sh 'curl -LO https://dl.k8s.io/release/v1.26.3/bin/linux/amd64/kubectl'
sh 'chmod u+x ./kubectl'
sh './kubectl rollout restart deployment ${APPLICATION_NAME}'
}
} else {
sh '''
# Create new app ...
'''
}
}
}
}
}
}