I have a declarative Jenkins pipeline. I am trying to pass Jenkins build parameters like jira_id and repository name along with credentials to the dockerfile as arguments.
However, on execution, the dockerfile is not able to receive any arguments as passed below.
May I please know the correct way of doing it?
Jenkinsfile Stage
stage('Create Image'){
steps{
script{
withCredentials([usernamePassword(credentialsId: 'admin', passwordVariable: 'admin_pw', usernameVariable: 'admin_user')]){
dir("${WORKSPACE}/jenkins/"){
def repo=docker.build("latest","--build-arg admin_user=$admin_user --build-arg admin_pw=$admin_pw --build-arg jira_id=$jira_id --build-arg repository_name=$repository_name --no-cache .")
}
}
}
}
}
Dockerfile
FROM centos:8
RUN echo "$repository_name, $jira_id, $admin_user"
3
Answers
Found the solution. In the dockerfile, I have to receive all the variables using ARG. ARG jira_id=$jira_id
There is difference between using
ARG
andENV
.ARG
can be set during the image build with –build-arg and you can’t access them anymore once the image is built.ENV
values are accessible during the build, and afterwards once the container runs. You can set ENV values in your Dockerfile.The Jenkinsfile stage is correct.
Changes in Dockerfile
While the above answers are correct, it fails if, you need dynamic naming in the "1st line" of Dockerfile i.e. if you have multiple repos to pull for same build it could look like this:
To make it work, I used
sed
with ENV in a different way, define ENV outside Dockerfile in your jenkins stage using something like this:env.CORP_REPO = "${params.corp_repo}/centos:latest"
My jenkins stage looks something like this:
Here,
sh 'sed -i "1c$CORP_REPO" Dockerfile'
is replacing the First line with the dynamic repo name set using ENV.You can play around with it.
Again, this works for nth number lines as you are defining scope outside your Dockerfile.
Cheers!