I’m trying to use sshagent plugin to deploy to remote server.
when using below syntax, I’m getting
pipeline {
agent any
stages {
stage('Deploy') {
steps {
sshagent(['nginx-ec2']) {
// some block
sh "ssh -o StrictHostKeyChecking=no ubuntu@<host_ip>"
sh "whoami"
}
}
}
}
}
getting output:
[Pipeline] sh (hide)
+ whoami
jenkins
while I’m expecting to run script at the remote server using provided credentials !!
So, I had to run it this way
pipeline {
agent any
stages {
stage('Deploy') {
steps {
sshagent(['nginx-ec2']) {
// some block
sh "ssh -o StrictHostKeyChecking=no -l ubuntu <host_ip> 'whoami &&
sudo apt update && sudo apt install -y docker.io &&
sudo usermod -aG docker ubuntu &&
source .bashrc &&
docker run -d nginx'"
}
}
}
}
}
Is there any "clean" way to run script on remote server with ubuntu instead of jenkins user ?
Edit:
I understand I need to run it under the ssh command not as separate sh script otherwise, it will run as jenkins and I’m able to do it in the scripted way as below.
That’s why I’m asking if there’s a better way to write it in the declarative way.
node {
stage('Deploy'){
def dockerRun = "whoami &&
sudo apt update && sudo apt install -y docker.io &&
sudo usermod -aG docker ubuntu &&
source .bashrc &&
docker run -d nginx "
sshagent(['nginx-ec2']) {
sh "ssh -o StrictHostKeyChecking=no ubuntu@<host_ip> '${dockerRun}' "
}
}
}
Thanks,
2
Answers
Well, so far this is the best way to do so, in-spite of repetition!
As noted, you should select a credential which does reference the right remote username, as seen in the SSH Agent Jenkins plugin:
Plus, I would execute only one script which would have the all sequence of commands you want to execute remotely.