How do I connect to a server via SSH with SSH-keypair in Jenkins pipeline?

Viewed 825

I'm trying to execute shell commands on a target server via jenkins pipeline. I tried multiple versions of my script:

  1. sshCommand with remote-set and secret file with private key

In the environment i configured:

sshkey = credentials('secret_file_with_private_key')

And then i tried executing it in a step:

        remote.name = "master"
        remote.host = "testserver"
        remote.user = "jenkins"
        remote.identityFile = "${sshkey}"
        sshCommand remote: remote, command: 'cat /tmp/test'

but i get the following results:

com.jcraft.jsch.JSchException: Auth fail

It doesn't even really "try" a login, atleast that is what i saw in /var/log/auth.log. It gives a disconnect with the Exception as a message to the server.

  1. withCredentials with secret file (private key)
    withCredentials([file(credentialsId: 'secret_file_with_private_key', variable: 'keyfile')]) {
            sh "ssh -o StrictHostKeyChecking=no -i ${keyfile} jenkins@testserver cat /tmp/test"
    }

I get a different message, that i don't quite understand:

+ ssh -o StrictHostKeyChecking=no -i **** jenkins@testserver cat /tmp/test
Warning: Identity file **** not accessible: No such file or directory.
Permission denied, please try again.
Permission denied, please try again.
jenkins@testserver: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).

Edit: 3. Credential "SSH Username and Secret key"

withCredentials([sshUserPrivateKey(credentialsId: secret_file_with_private_key', keyFileVariable: 'identity', usernameVariable: 'userName')]) {
        remote.user = userName
        remote.identityFile = identity
        sshCommand remote: remote, command: "cat /tmp/test"

This version also gave me the Exception you see in 1.

When i use the private key in KeePass as my keyagent and login via putty, it works perfectly fine.

Maybe important: The key doesn't have a passphrase.

I configured the secret file in the jenkins credentials option but don't know why it can't access it. Any ideas?

0 Answers
Related