When I connect to the AWS EC2 instance using ssh for the first time, I got an error like below because the host key is not stored in ssh known_hosts file.
The authenticity of host 'x.x.x.x' can't be established. ECDSA key fingerprint is xx:yy:.... Are you sure you want to continue connecting (yes/no)?
Now, I'm automating ssh. I often just add StrictHostKeyChecking option to ssh command to avoid this message. But, I feel that is not very safe way and possibly cause Man in the middle attack. Is there any (or good) way to get host key safely on AWS EC2?
I think the only way is to parse the console output.
#get the console output of the instance
aws ec2 get-console-output --instance-id <instance id> |\
#use jq to get the Output field
jq .Output -r |\
#use sed to find the interesting bits
sed -n -e '1,/-----BEGIN SSH HOST KEY KEYS-----/d; /-----END SSH HOST KEY KEYS-----/q; p'
Caveats, which might not matter depending on your application:
aws
output is JSON, so we need to parse itIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With