title: SSH into a remote server in a Jenkins pipeline using withCredentials
body: <p>I want to SSH into a server to perform some tasks in my Jenkins pipeline.</p>
  
  <p>Here are the steps that I went through.</p>
  
  <ol>
  <li>In my remote server, I used <code>ssh-keygen</code> to create <code>id_rsa</code> and <code>id_rsa.pub</code></li>
  <li>I copied the string in the <code>id_rsa</code> and pasted to the <code>Private Key</code> field in the <code>Global Credentials</code> menu in my Jenkins server.</li>
  </ol>
  
  <p><a href="https://i.stack.imgur.com/biAVg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/biAVg.png" alt="enter image description here"></a></p>
  
  <ol start="3">
  <li><p>In my Jenkinsfile, I do</p>
  
  <p><code>stage('SSH into the server') {
              steps {
                  withCredentials([sshUserPrivateKey(
                      credentialsId: '&lt;ID&gt;',
                      keyFileVariable: 'KEY_FILE')]) {
                      sh '''
                      more ${KEY_FILE}
                      cat ${KEY_FILE} &gt; ./key_key.key
                      eval $(ssh-agent -s)
                      chmod 600 ./key_key.key
                      ssh-add ./key_key.key
                      cd ~/.ssh
                      echo "ssh-rsa ... (the string from the server's id_rsa.pub)" &gt;&gt; authorized_keys
                      ssh root@&lt;server_name&gt; docker ps
                      '''
                  }
              }
          }</code></p></li>
  </ol>
  
  <p>It pretty much creates an <code>ssg-agent</code> using the private key of the remote server and adds a public key to the authorized key.</p>
  
  <p>This as a result gives me, <code>Host key verification failed</code></p>
  
  <p>I just simply wanted to ssh into the remote server, but I keep facing this issue. Any help?</p>
  
  <p><strong>LOG</strong></p>
  
  <pre><code>++ ssh-agent -s
  + eval 'SSH_AUTH_SOCK=/tmp/ssh-xfcQYEfiyfRs/agent.26353;' export 'SSH_AUTH_SOCK;' 'SSH_AGENT_PID=26354;' export 'SSH_AGENT_PID;' echo Agent pid '26354;'
  ++ SSH_AUTH_SOCK=/tmp/ssh-xfcQYEfiyfRs/agent.26353
  ++ export SSH_AUTH_SOCK
  ++ SSH_AGENT_PID=26354
  ++ export SSH_AGENT_PID
  ++ echo Agent pid 26354
  Agent pid 26354
  + chmod 600 ./key_key.key
  + ssh-add ./key_key.key
  Identity added: ./key_key.key (./key_key.key)
  + ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i ./key_key.key root@&lt;server&gt; docker ps
  Warning: Permanently added '&lt;server&gt;, &lt;IP&gt;' (ECDSA) to the list of known hosts.
  
                                   WARNING!!!
                      READ THIS BEFORE ATTEMPTING TO LOGON
  
        This System is for the use of authorized users only.  ....
  
  
  
  Permission denied, please try again.
  Permission denied, please try again.
  Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
  </code></pre>