jenkinsamazon-ec2ssh-keys

Jenkins EC2 agent - Host key verification failed


I'm using Jenkins EC2 Plugin to spawn agents on demand. During my job I have to clone other repository, so I'm using sshagent. However I was getting Host key verification failed error, so I've added: sh 'ssh-keygen -F github.company.com || ssh-keyscan -H -t rsa github.company.com >> ~/.ssh/known_hosts' before cloning, which doesn't solve my problem. I'm really confused by output I'm getting:

+ ssh-keygen -F github.company.com
2024-06-03 11:02:03.310  Cannot stat /home/ubuntu/.ssh/known_hosts: No such file or directory
2024-06-03 11:02:03.310  + ssh-keyscan -H -t rsa github.company.com
2024-06-03 11:02:03.310  /home/ubuntu/workspace/job-name@tmp/durable-b8889414/script.sh.copy: line 1: /home/ubuntu/workspace/job-name/.ssh/known_hosts: No such file or directory

It looks like script tries to find known_hosts in in home directory, but if it doesn't then tries to add to known_hosts in different place. Could somebody explain me this behavior or how it should look like?


Solution

  • ~ expansion is broken for whatever reason. Try using $HOME instead, that is more reliable.

    sh 'ssh-keygen -F github.company.com || ssh-keyscan -H -t rsa github.company.com >> $HOME/.ssh/known_hosts'
    

    Keep single quotes, changing to double quotes would expand $HOME too early.