Search code examples
dockerjenkinsjenkins-pipelinessh-keys

Jenkinsfile with docker agent not able to load ssh key


I have a simple pipeline:

pipeline {
    agent {
        docker {
            image 'python:3.8-alpine3.15'
        }
    }
...
steps {
       withCredentials([sshUserPrivateKey(credentialsId: "repo", keyFileVariable: 'keyfile')]){
             sh '''
             set +x
             eval `ssh-agent -s`
             ssh-add ${keyfile}
             git clone [email protected]/blabla
             '''

      }
   }
}

The errored output is:

Masking supported pattern matches of $keyfile
Agent pid 53
+ ssh-add **** ([email protected])
...
Host key verification failed.
fatal: Could not read from remote repository.

I have tried the same steps with the same key step by step on the same machine and it works, the problem resides on the withCredentials binding. It is not viable to change to ssh-agent plugin.

Does anybody know what is wrong and why I can't load the credentials succesfully?


Solution

  • After lots of debugging, what worked for me was:

    • SSH Agent implementation (plugin download required, not good)
    pipeline {
        agent {
            docker {
                image 'python:3.8-alpine3.15'
            }
        }
    ...
    steps {
           sshagent(credentials: ['repo']) {
                 sh '''
                 set +x
                 mkdir ~/.ssh
                 ssh-keyscan gitlab.com >> ~/.ssh/known_hosts
                 git clone [email protected]/blabla
                 pip install -r requirements.txt
                 '''
          }
       }
    }
    

    Finally I ended up using sshagent plugin, otherwise if you need to use withCredentials plugin you should consider:

    • Vanilla Implementation (no extra plugin download, good)
    pipeline {
        agent {
            docker {
                image 'python:3.8-alpine3.15'
            }
        }
    ...
    steps {
           withCredentials([sshUserPrivateKey(credentialsId: "repo", keyFileVariable: 'keyfile')]) {
                 sh '''
                 set +x
                 mkdir ~/.ssh
                 ssh-keyscan gitlab.com >> ~/.ssh/known_hosts
                 eval `ssh-agent -s`
                 ssh-add ${keyfile}
                 git clone [email protected]/blabla
                 pip install -r requirements.txt
                 '''
          }
       }
    }
    

    Personally I consider the implementation with withCredentials much more approachable because you do not depend on external plugin.

    External references:

    With those two implementations, you should not have any problem when passing ssh keys onto a pipeline which is ran inside a docker container.

    Free software.