Reputation: 15394
I am just starting to look at Jenkins Declarative pipeline and running my builds in a docker container. I have a project that pulls in NPM packages via Git and thus need to have SSH keys set.
From what I have come across I can set build args such as --build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa.pub)"
and then in my Dockerfile
ARG ssh_pub_key
I have taken the following approach within my Jenkinsfile
pipeline {
agent {
dockerfile {
args '''--build-arg ssh_prv_key="$(cat /var/lib/jenkins-git/.ssh/id_rsa)"'''
}
}
stages {
stage('Test') {
steps {
sh 'echo $ssh_prv_key'
}
}
}
}
When running the build in Jenkins I get the below output when building the image (no mention of the --build-arg
):
docker build -t 085eb412f6dd28c1a7843aa9f9ed84e7c4af3e1b -f Dockerfile .
and nothing for the variable.
Am I not setting them correctly? Is there another way to handle the copying of keys?
My Jenkinsfile now looks like below but will not run as get
Required context class hudson.FilePath is missing
Perhaps you forgot to surround the code with a step that provides this, such as: node
It seems I can't run any scripts outside of the pipeline declarative ?
def ssh_prv_key = sh script: 'cat /var/lib/jenkins-git/.ssh/id_rsa', returnStdout: true
def ssh_pub_key = sh script: 'cat /var/lib/jenkins-git/.ssh/id_rsa.pub', returnStdout: true
pipeline {
agent {
dockerfile {
args """--build-arg ssh_prv_key=\"${ssh_prv_key}\" --build-arg ssh_pub_key=\"${ssh_pub_key}\" """
}
}
stages {
stage('Test') {
steps {
sh 'echo $ssh_prv_key'
}
}
}
}
Upvotes: 1
Views: 1595
Reputation: 38992
Here $(cat /var/lib/jenkins-git/.ssh/id_rsa)
is a shell command.
AFAIK, bindings must have been declared outside of the pipeline line to use them when defining agents.
So, make the pipeline job parameterized.
ssh_prv_key
as a Credentials Parameter. Secretfile
ssh_pub_key
Then use ssh_prv_key
in dockerfile
additionalBuildArgs
directive.
pipeline {
agent {
dockerfile {
additionalBuildArgs ""--build-arg ssh_prv_key=\"$ssh_prv_key\" --build-arg ssh_pub_key=\"$ssh_pub_key\""
}
}
stages {
stage('Test') {
steps {
sh "echo $ssh_prv_key"
}
}
}
}
Upvotes: 1