Miguel Mesquita Alfaiate
Miguel Mesquita Alfaiate

Reputation: 2968

Jenkins Pipeline inside docker container with SSH file transfer using SSH Key

I am trying to migrate a teamcity pipeline to a jenkins one.

I am used to teamcity, and I still finding my way around Jenkins, but I haven't found a way to do this.

I want to have a pipeline with 2 steps, one for compiling an application, and a second step to send it to a server using SSH with private keys.

I can easily do that in Teamcity (after some research) but with Jenkins I have researched it and haven't found a way to get there, nor examples over the web.

I have tried a freestyle project where I can configure SSH agent but I can't seem to find where to place the rest of the logic, and a multibranch pipeline which uses a Jenkinsfile within the repo to compile, but nowhere to set details for sending files over.

Should I use a multibranch pipeline and "send" the files from within the jenkinsfile? If so, how do I tell Jenkins to make the key available to the docker container?

Or should I use the freestyle project, and if so, how do I tell it to use the Jenkinsfile first, and then send the resulting file or files to the destination server?

Or should I use something completely different?

Upvotes: 0

Views: 2997

Answers (1)

EricD
EricD

Reputation: 316

You can do that in a pipeline :

1/ Add your private key to Jenkins by creating a new credential (ssh Username with private key)

2/ In a jenkinsFile :

node {
try {

    stage ("build") {

        dir('Build') {

            env.NODEJS_HOME = "${tool 'Node 12.12'}"
            env.PATH="${env.NODEJS_HOME}/bin:${env.PATH}"
            sh 'npm install'
            sh 'npm pack'  
        }
    }

    stage ("Deploy") {

            def remote = [:]
            remote.name = 'name of your server'
            remote.host = 'ip of your server'
            remote.allowAnyHosts = true

        dir ('Build') {

            withCredentials([sshUserPrivateKey(
                credentialsId: 'id_of_your_previously_created_credential',
                keyFileVariable: 'identityKey',
                passphraseVariable: 'passphraseV',
                usernameVariable: 'userR')])  
                {
                remote.user = userR
                remote.passphrase = passphraseV
                remote.identityFile = identityKey
                sshPut remote: remote, from: "yourArchive.tgz", into: '.'
                }
        }
    } 

} catch (e) {
  println "Caught: ${e}"
  throw e    
} 

}

I've used npm for the exemple, with 'npm pack' creating an archive that we will upload to a server.

You might also need to install (if not already done) the following Plugin:

  • SSH Credentials Plugin
  • SSH Pipeline Steps
  • Credentials Binding Plugin
  • Credentials Plugin

Upvotes: 2

Related Questions