Search code examples
amazon-web-servicesamazon-ec2

EC2 get SSH host keys from an instance via boto3


A python script launches an instance. The script then needs to log in via SSH into it. But to pass the SSH host verification it has to get the host public keys that were generated on the instance during the launch.

These keys are usually printed in the console logs of the instance:

-----BEGIN SSH HOST KEY KEYS-----
...
-----END SSH HOST KEY KEYS-----

How to get this information via the boto3 API? One way I can think of is to write that info from the user cloud-init script of the instance into an s3 storage and then make python script read it. Is there a better way? Custom tags that can be added to an ec2 instance from within the instance?


Solution

  • Rather than generating new keys every time an instance is launched, you can simply specify an existing key when launching the EC2 instance. This way, it can always use the same keypair and your process is greatly simplified.

    By the way, there should be very little need for a program to use an SSH connection into another computer. If you are wanting to run a script on another computer, you can do it via User Data (for initial launch), or use the AWS Systems Manager Run Command - AWS Systems Manager to run scripts on existing Amazon EC2 instances.