Neither "StrictHostKeyChecking no" nor "ssh-keyscan" options are secure. you need a manual fingerprint validation at some point to avoid MiTM attack if you stick with ssh.
Actually, you have 2 options:
Use https protocol instead of git
It won't ask you for a fingerprint, because ssh is not involved, https is used instead. For a security standpoint you are trusting root certificates installod on your OS. If you're using a minimalist image or Docker, you might need to install the ca-certificates package.
If you really want git+ssh protocol
Do you really need to add the key at runtime? This is not secure because you didn't check the fingerprint and that leaves you open to MiTM attacks. This is not just theoretical, and it has been proven to work.
Before running your script, get the key from github (on your local machine):
ssh-keyscan github.com > githubKey
Generate the fingerprint:
ssh-keygen -lf githubKey
And check it manually against those listed in this page (ok, there you trust https certificates and OpenSSL to bring you the original github website, but it's still a lot better than blindly accepting a public key).
Alternatively (trusting the same https and OpenSSL) you can fetch it from https://api.github.com/meta like this: curl -s https://api.github.com/meta | jq ."ssh_key_fingerprints" | grep RSA
. (Thanks @willscripted for this one)
Then, you hardcode it in your script by adding in it:
echo '<copy paste the content of 'cat githubKey' on your machine>' >> ~/.ssh/known_hosts
before the git clone.
The GitHub public key will only change if they believe it was compromised (or not secure enough). If this is ever the case, you want your script to fail anyway.