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
sshagentneeds 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
How to Deploy a Static Site to S3 With JenkinsDeploy a built static site to an S3 bucket from a Jenkins Declarative Pipeline using aws s3 sync, then invali…
How to Gate a Production Deploy With Input and Timeout in JenkinsGate a production deploy in Jenkins behind a manual approval that auto-aborts after a timeout, wrapping the i…