1

My Jenkins pipeline code successfully checks out my private git repo from bitbucket using

checkout([$class: 'GitSCM',
            userRemoteConfigs: [[credentialsId: 'cicd-user', url:'ssh://git@bitbucket.myorg.co:7999/A/software.git']]

in same software.git I have a Dockerfile that I want to use to build various build targets present in software.git on Kubernetes and I am trying the below to pass jenkins credentials into a docker container that I want to build and run.

So in the same jenkins pipeline when I checked out software.git (above code), I try to do the following to get the docker container built

  withCredentials([sshUserPrivateKey(credentialsId: 'cicd-user', keyFileVariable: 'FILE')]) { 
           sh "cd ${WORKSPACE} && docker build -t ${some-name} --build-arg USERNAME=cicd-user --build-arg  PRIV_KEY_FILE=$FILE --network=host -f software/tools/jenkins/${some-name}/Dockerfile ."
        }

in Dockerfile I do

RUN echo "$PRIV_KEY_FILE" > /home/"$USERNAME"/.ssh/id_rsa && \
 chmod 700 /home/"$USERNAME"/.ssh/id_rsa 

RUN echo "Host bitbucket.myorg.co\n\tStrictHostKeyChecking no\n" >> ~/.ssh/config

But still from my Docker container I am not able to successfully checkout my private repo(s). What am I missing ? Any comments, suggestions ? Thanks.

a k
  • 531
  • 5
  • 15

1 Answers1

2

Please read about Groovy String Interpolation.

In your expression

sh "cd ${WORKSPACE} && docker build -t ${some-name} \
--build-arg USERNAME=cicd-user \
--build-arg  PRIV_KEY_FILE=$FILE --network=host \
-f software/tools/jenkins/${some-name}/Dockerfile ."

you use double quotes so Groovy interpolates all the variables in the string. This includes $FILE so Groovy replaces that with the value of Groovy variable named FILE. You don't have any Groovy variable with that name (but rather bash variable which is different from Groovy) so this gets replaced with an empty string.

To prevent interpolating that particular variable, you need to hint Groovy not to interpolate this particular one, by escaping this $ with \:

sh "cd ${WORKSPACE} && docker build -t ${some-name}\
 --build-arg USERNAME=cicd-user \
 --build-arg  PRIV_KEY_FILE=\$FILE --network=host \
 -f software/tools/jenkins/${some-name}/Dockerfile ."
MaratC
  • 6,418
  • 2
  • 20
  • 27
  • Thanks that helped to move forward, but I am getting a new issue "Load key "/home/cicd-user/.ssh/id_rsa" :(invalid format) "git@Bitbucket.mycomp.co:Permission denied( Public key) "fatal: could not read from remote repository" Any idea on what might be going wrong or where I should be looking for debugging this correctly ? – a k Feb 15 '21 at 05:00
  • I can suggest accepting my answer if it solved your issue, and asking a new question with details :) – MaratC Feb 15 '21 at 10:01
  • Posted a follow up question here https://stackoverflow.com/questions/66211996/how-to-correctly-pass-ssh-key-file-from-jenkins-credentials-variable-into-to-doc – a k Feb 15 '21 at 17:31