If you have ever been in the annoying situation where you had to run
git clone from a server that you did not have interactive access to, such as a continuous integration/deployment box or other. Then you may have run into the dreaded
Are you sure you want to continue connecting (yes/no)? dialogue.
Usually, at this stage, you would be stuck, as you need a way to tell it
yes, but there’s no input!
A nice trick around this is to add the host to your
known_hosts file beforehand.
First, let’s see how to get around this
This is easy enough to do if you know the host you need to add. In my case, it was
ssh-keyscan github.com >> ~/.ssh/known_hosts
Obviously, you could do the same with any host needed, perhaps you have a Bitbucket host, or a Github Enterprise host, maybe even Gitlab or something else.
ssh-keyscan <whatever_host_you_need_for_example_>github.com >> ~/.ssh/known_hosts
Now let’s make it better!
The above code works pretty well, but it will add the new entry into our
known_hosts file each time it’s run, even if it already exists. This is not very clean. So let’s make it better!
ssh-keygen -F github.com || ssh-keyscan github.com >> ~/.ssh/known_hosts
What this does, is checks to see if the system already knows about this host, and only if it doesn’t, will it add it.