Skip to content
Latchkey

How to Deploy Over SSH to a VPS With Jenkins

sshagent loads an SSH private key into the agent so rsync and ssh authenticate without a password prompt.

Store an SSH private key credential, wrap deploy commands in sshagent(["key-id"]), then rsync the artifact and run a remote restart over ssh.

Steps

  • Add the deploy SSH private key as an SSH Username with private key credential.
  • Wrap the deploy in sshagent(["ssh-deploy-key"]).
  • rsync the build to the host, then run the remote restart via ssh.

Pipeline

Jenkinsfile
pipeline {
  agent any
  stages {
    stage('Deploy') {
      steps {
        sshagent(['ssh-deploy-key']) {
          sh '''
            rsync -az --delete dist/ deploy@vps.example.com:/var/www/app/
            ssh -o StrictHostKeyChecking=accept-new deploy@vps.example.com \
              'sudo systemctl restart app'
          '''
        }
      }
    }
  }
}

Gotchas

  • sshagent needs the SSH Agent plugin; install it before referencing the step.
  • Pre-seed the host key (or use accept-new) so the first connection does not hang on a prompt.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →