Jenkins ssh-agent starts and then stops immediately in pipeline build Jenkins ssh-agent starts and then stops immediately in pipeline build jenkins jenkins

Jenkins ssh-agent starts and then stops immediately in pipeline build


I recently had a similar issue though it was inside a docker container.The logs gave the impression that ssh-agent exits too early but actually the problem was that I had forgotten to add the git server to known hosts.

I suggest ssh-ing onto your jenkins master and trying to do the same steps as the pipeline does with ssh-agent (the cli). Then you'll see where the problem is.

E.g:

eval $(ssh-agent -s)ssh-add ~/yourKeygit clone

As explained on help.github.com

Update:Here a util to add knownHosts if not yet added:

/** * Add hostUrl to knownhosts on the system (or container) if necessary so that ssh commands will go through even if the certificate was not previously seen. * @param hostUrl */void tryAddKnownHost(String hostUrl){    // ssh-keygen -F ${hostUrl} will fail (in bash that means status code != 0) if ${hostUrl} is not yet a known host    def statusCode = sh script:"ssh-keygen -F ${hostUrl}", returnStatus:true    if(statusCode != 0){        sh "mkdir -p ~/.ssh"        sh "ssh-keyscan ${hostUrl} >> ~/.ssh/known_hosts"    }}


I was using this inside docker, and adding it to my Jenkins master's known_hosts felt a bit messy, so I opted for something like this:

  1. In Jenkins, create a new credential of type "Secret text" (let's call it GITHUB_HOST_KEY), and set its value to be the host key, e.g.:
# gets the host for github and copies it. You can run this from# any computer that has access to github.com (or whatever your# git server is)ssh-keyscan github.com | clip
  1. In your Jenkinsfile, save the string to known_hosts
pipeline {    agent { docker { image 'node:12' } }    stages {        stage('deploy-staging') {            when { branch 'staging' }            steps {                withCredentials([string(credentialsId: 'GITHUB_HOST_KEY', variable: 'GITHUB_HOST_KEY')]) {                    sh 'mkdir ~/.ssh && echo "$GITHUB_HOST_KEY" >> ~/.ssh/known_hosts'                }                sshagent(['my-credentials-id']) {                    sh 'git push joe@repo:project'                }            }        }    }}

This ensures you're using a "trusted" host key.