Jenkins pipeline not correctly using sshagent credentials - jenkins

I have this code snippet that has to use a custom private key from the Jenkins credentials using the ssh-agent-plugin.
This doesn't seem to work, but it also doesn't print a very useful output.
Any ideas how to debug this?
stage('Test Git') {
steps {
sshagent(credentials : ['denpal']) {
sh 'git commit --allow-empty -m "test withCredentials"'
sh 'git push origin feature/Jenkinsfile'
}
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Test Git)
[Pipeline] sshagent
[ssh-agent] Using credentials git (denpal)
[ssh-agent] Looking for ssh-agent implementation...
[ssh-agent] Exec ssh-agent (binary ssh-agent on a remote machine)
$ ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-WEsIsQvX4CFc/agent.12163
SSH_AGENT_PID=12166
Running ssh-add (command line suppressed)
[Pipeline] // sshagent
[Pipeline] }

I had the same problem trying to push code to my repo from Jenkins.
I found the solution here: https://www.reddit.com/r/docker/comments/b8lmc4/jenkins_pipeline_not_correctly_using_sshagent/
I replaced the sshagent code block with:
withCredentials([sshUserPrivateKey(credentialsId: 'myCredentials', keyFileVariable: 'KEY_FILE')]) {
sh "eval `ssh-agent -s` && ssh-add ${KEY_FILE} && ssh-add -L && git push -u origin develop"
}
It worked for me.

Related

jenkins ssh agent fail to copy war to remote server

I am new to jenkin, I have created a jenkinFile to build a war and copy it to a remote machine on tomcat server based on the following tutorial:
https://thenucleargeeks.com/2020/05/31/declarative-jenkins-pipeline-to-deploy-java-web-application/
Please find below jenkinFile which i have created:
#!/usr/bin/env groovy
pipeline {
environment {
NAME = readMavenPom().getArtifactId()
}
agent any
options {
timeout(time: 1, unit: 'HOURS')
buildDiscarder(logRotator(daysToKeepStr: '10', numToKeepStr: '5', artifactNumToKeepStr: '2'))
}
stages {
stage("Git Checkout"){
steps{
git branch: 'develop',
credentialsId: 'jenkins', url: 'https://gitlab.gov/ih/ih-por.git'
}
}
stage('Maven build') {
steps {
sh "mvn clean package"
sh "mv target/*.war target/UI.war"
}
}
stage("deploy-dev"){
steps{
sshagent(['user-id-tomcat-deployment']) {
sh """
scp -o StrictHostKeyChecking=no target/UI.war
root#192.168.1.000:/opt/tomcat/webapps/
ssh root#192.168.1.000 /opt/tomcat/bin/shutdown.sh
ssh root#192.168.1.000 /opt/tomcat/bin/startup.sh
"""
}
}
}
}
}
I have also created added the private key on my jenkin server.
However when I build the project on jenkins the following error is displayed by ssh agent:
[Pipeline] { (deploy-dev)
[Pipeline] sshagent (hide)
[ssh-agent] Using credentials root (This defines the credential to login remote server where tomcat is installed for deployment purpose)
[ssh-agent] Looking for ssh-agent implementation...
[ssh-agent] Exec ssh-agent (binary ssh-agent on a remote machine)
$ ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-r2GnAq9cX2F8/agent.37244
SSH_AGENT_PID=37247
Running ssh-add (command line suppressed)
Identity added: /var/lib/jenkins/workspace/InfoHighway/portal-ui-deploy#tmp/private_key_6145932096571627059.key (root#localhost.localdomain)
[ssh-agent] Started.
[Pipeline] {
[Pipeline] sh
+ scp -o StrictHostKeyChecking=no target/portalUI.war
usage: scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]
[-l limit] [-o ssh_option] [-P port] [-S program]
[[user#]host1:]file1 ... [[user#]host2:]file2
[Pipeline] }
$ ssh-agent -k
unset SSH_AUTH_SOCK;
unset SSH_AGENT_PID;
echo Agent pid 37247 killed;
[ssh-agent] Stopped.
[Pipeline] // sshagent
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // timeout
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code 1
Finished: FAILURE
Any idea what I am doing wrong please?
You have a new line after the target/UI.war so the scp command is missing the target parameter.
Try to run it with the full scp command in a single line:
stage("deploy-dev"){
steps{
sshagent(['user-id-tomcat-deployment']) {
sh """
scp -o StrictHostKeyChecking=no target/UI.war root#192.168.1.000:/opt/tomcat/webapps/
ssh root#192.168.1.000 /opt/tomcat/bin/shutdown.sh
ssh root#192.168.1.000 /opt/tomcat/bin/startup.sh
"""
}
}
}

Running ssh-agent within docker on jenkins doesnt work

I am trying to use a container within my jenkins pipeline, however I cant get ssh-agent to work inside it. I am on v1.19 of the plugin, when I run the below code I get
Host key verification failed. fatal: Could not read from remote
repository.
Please make sure you have the correct access rights and the repository
exists.
However if I run the code from outside the image it works perfect, proving that the user has the correct permissions.
node('nodeName'){
cleanWs()
ws("short"){
withDockerRegistry([credentialsId: 'token', url: "https://private.repo.com"]) {
docker.image("img:1.0.0").inside("-u root:root --network=host") {
sshagent(credentials: ["bitbucket_token"]) {
sh "mkdir ~/.ssh"
sh 'ssh-keyscan bitbucket.company.com >> ~/.ssh/known_hosts'
sh 'git clone ssh://git#bitbucket.company.com:PORT/repo.git'
}
}
}
}
}
Here is the output:
[Pipeline] sshagent
[ssh-agent] Using credentials jenkins (bitbucket_token)
[ssh-agent] Looking for ssh-agent implementation...
[ssh-agent] Exec ssh-agent (binary ssh-agent on a remote machine)
$ docker exec abcdef123456 ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-qwertyu/agent.15
SSH_AGENT_PID=22
Running ssh-add (command line suppressed)
Identity added: /home/jenkins/short#tmp/private_key_8675309.key (/home/jenkins/short#tmp/private_key_8675309.key)
[ssh-agent] Started.
[Pipeline] {
[Pipeline] sh
+ mkdir /root/.ssh
[Pipeline] sh
+ ssh-keyscan bitbucket.company.com
# bitbucket.company.com:22 SSH-2.0-OpenSSH_6.6.1
# bitbucket.company.com:22 SSH-2.0-OpenSSH_6.6.1
# bitbucket.company.com:22 SSH-2.0-OpenSSH_6.6.1
[Pipeline] sh
+ git clone ssh://git#bitbucket.company.com:PORT/repo.git
Cloning into 'repo'...
Host key verification failed.
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
[Pipeline] }
$ docker exec --env ******** --env ******** abcdef123456 ssh-agent -k
unset SSH_AUTH_SOCK;
unset SSH_AGENT_PID;
echo Agent pid 22 killed;
[ssh-agent] Stopped.
[Pipeline] // sshagent
Im completely stumped by this

Jenkins ssh agent plugin is getting stacked, No error, no timeout issue

I installed jenkins ssh agent plugin. I created ssh private key on the linux server(using ssh-keygen -t rsa command) I am trying to connect. Then under jenkins credintials added SSH Username with private key with all required fields. In jenkinsfile added simple command to run over ssh:
pipeline {
agent any
stages {
stage('---doingsomething---') {
steps {
sshagent (credentials: ['jbowner-195']) {
sh 'ssh -o StrictHostKeyChecking=no -l jbowner 10.10.23.195 uname -a'
}
}
}
}
}
When I press build button process is starting and never ending. No error, no timeout issue.
Here is piece of output on which jenkins stacks
[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (---echoing---)
[Pipeline] sshagent
[ssh-agent] Using credentials jbowner (jbowner 10.10.23.195)
[ssh-agent] Looking for ssh-agent implementation...
[ssh-agent] Exec ssh-agent (binary ssh-agent on a remote machine)
$ ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-XSQPEUHOqZQR/agent.10226
SSH_AGENT_PID=10229
Running ssh-add (command line suppressed)
Identity added: /home/jenkins/.jenkins/workspace/Eformgenerator-Prod#tmp/private_key_5151715321960722060.key (/home/jenkins/.jenkins/workspace/Eformgenerator-Prod#tmp/private_key_5151715321960722060.key)
[ssh-agent] Started.
[Pipeline] {
[Pipeline] sh
+ ssh -o StrictHostKeyChecking=no -l jbowner 10.10.23.195 uname -a
any ideas?
Jenkins ssh plugin didn't work for me. My solution is
generate rsa keys on source machine using ssh-keygen -t rsa
ssh-copy-id username#destination_ip. Then enter destination password. This will add as destination ip as a known host and adds source key on the destination machine as a authorized key.
then instead of using jenkins ssh agent I used standard ssh command like this.
pipeline {
agent any
stages {
stage('---echoing---') {
steps {
sh 'ssh -o StrictHostKeyChecking=no jbowner#10.10.23.195 uptime'
}
}
}
}
This is working because servers have been trusting each other using ssh key

Jenkins Pipeline - ssh-agent can't find credentials

I have a task that's been working through the GUI as a Freestyle project. I'm trying to follow all of the instructions and documentation I can find to convert it to a Pipeline job, but I'm getting errors.
Here are the credentials I've created for the action.
I'm trying a fairly simple test to run a command on a remote Windows server.
#!/usr/bin/env groovy
pipeline {
agent any
stages {
stage("build") {
steps {
sshagent(credentials: ['1c0972a6-2bbf-4144-XXXX-XXXXXXXXXXXX']) {
sh """
ssh "dev user#XX.XX.XX.XX" su -c "powershell /project/getproj.bat | tee build.log"
"""
}
}
}
}
}
Finally, heres the output log.
Started by user XXXX XXXX
Obtained Jenkinsfile from git https://xx.xx.com/xxxx.git
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /var/jenkins_home/workspace/Testing/xxxx
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Declarative: Checkout SCM)
[Pipeline] checkout
using credential 0d240009-1e30-4e3b-xxxx-xxxxxxxxxxxx
> git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
> git config remote.origin.url https://xx.xx.com/xxxx.git # timeout=10
Fetching upstream changes from https://xx.xx.com/xxxx.git
> git --version # timeout=10
using GIT_ASKPASS to set credentials
> git fetch --tags --progress https://xx.xx.com/xxxx.git +refs/heads/*:refs/remotes/origin/*
> git rev-parse refs/remotes/origin/convert_jenkinsfile^{commit} # timeout=10
> git rev-parse refs/remotes/origin/origin/convert_jenkinsfile^{commit} # timeout=10
Checking out Revision 40a510567b52ce621cb6590ab233289cb1948ad4 (refs/remotes/origin/convert_jenkinsfile)
> git config core.sparsecheckout # timeout=10
> git checkout -f 40a510567b52ce621cb6590ab233289cb1948ad4
Commit message: "Update Jenkinsfile"
> git rev-list --no-walk 6325e08c341a4e7e0cec8538640bd3d6cf6941fa # timeout=10
[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (build)
[Pipeline] sshagent
FATAL: [ssh-agent] Could not find specified credentials
[ssh-agent] Looking for ssh-agent implementation...
[ssh-agent] Exec ssh-agent (binary ssh-agent on a remote machine)
$ ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-pRQqteq1L7US/agent.49961
SSH_AGENT_PID=49964
[ssh-agent] Started.
[Pipeline] {
[Pipeline] sh
+ ssh dev user#xx.xx.xx.xx su -c powershell /project/getproj.bat | tee build.log
Host key verification failed.
[Pipeline] }
$ ssh-agent -k
unset SSH_AUTH_SOCK;
unset SSH_AGENT_PID;
echo Agent pid 49964 killed;
[ssh-agent] Stopped.
[Pipeline] // sshagent
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code 255
Finished: FAILURE
I can't tell if I'm doing something wrong with how I've identified the credentials, or there's something wrong in the Jenkinsfile. I'm intending to run multiple commands on the remote Windows server.
The ssh-agent plugin does not support user/password credentials.
It is not so easy to spot this information, but you can find that the plugin documentation says 'Note that only Private Key based credentials can be used.'
If you specify a credentials id referring to credentials of kind "Username with password", you always get "FATAL: [ssh-agent] Could not find specified credentials"
This might be related to JENKINS-32101. Please try the alternative syntax sshagent(['1c0972a6-2bbf-4144-XXXX-XXXXXXXXXXXX']) {...}.

Jenkins, Host key verification failed, script returned exit code 255

I have a building-server where I have Jenkins 2.73.3 and another servers where I deploy my apps.
I have also set up a credential to connect from building-server to the other servers.
But everytime I add another server it is difficult to add it because I set up the authorized key in the new server and in the command line works, but not in Jenkins.
Here is a little recipe that fails:
pipeline {
agent any
stages {
stage('Set conditions') {
steps {
sshagent(['xxxx-xxxx-xxxx-xxxx-xxxx']) {
sh "ssh user#product.company.com 'echo $HOME'"
}
}
}
}
}
And here is the Log failure:
[ssh-agent] Started.
[Pipeline] {
[Pipeline] sh
[check] Running shell script
+ ssh user#product.company.com echo /var/lib/jenkins
$ ssh-agent -k
unset SSH_AUTH_SOCK;
unset SSH_AGENT_PID;
echo Agent pid 12567 killed;
[ssh-agent] Stopped.
Host key verification failed.
[Pipeline] }
[Pipeline] // sshagent
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code 255
Finished: FAILURE
It seems that the solution was to add the parameter StrictHostKeyChecking to the shell script line
sh "ssh -o StrictHostKeyChecking=no user#product.company.com 'echo $HOME'"

Resources