SSH host keys are typically generated directly on the host to reduce the risk of them becoming available to another party that could therefore impersonate your host.
However, that typical practice conflicts with your requirements because you wish to intentionally reuse the same host key across multiple hosts, albeit hosts that will not exist concurrently for very long.
If you are using an AMI that handles user_data using cloud-init (which is likely if you're using a general-purpose Linux distribution image) then you can configure cloud-init to use predefined host keys by populating the ssh_keys argument for cloud-init's SSH module.
The cloud-init documentation inludes the following example of configuring a fixed RSA keypair:
ssh_keys:
rsa_private: |
-----BEGIN RSA PRIVATE KEY-----
MIIBxwIBAAJhAKD0YSHy73nUgysO13XsJmd4fHiFyQ+00R7VVu2iV9Qco
...
-----END RSA PRIVATE KEY-----
rsa_public: ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAGEAoPRhIfLvedSDKw7Xd ...
However, this approach has some security drawbacks:
- If you hard-code or generate a private key in your Terraform configuration then that key will be available to anyone who can access your Terraform state. Anyone who can access the key can deploy an SSH server that can impersonate yours.
- Amazon EC2 does not consider
user_data to be security-sensitive data, and so anyone who can retrieve the metadata about your EC2 instance through the EC2 API can also obtain your private key, with the same consequence.
Instead of using a fixed keypair to authenticate your host, your situation seems better-suited to using host certificates, because then you can set up a certificate authority that outlives any individual host and then use that certificate authority to issue a new certificate for each new host.
In this case the clients need only to trust the certificate authority's long-lived key and can use it to verify the temporary certificates issued to your hosts.
However, even this solution has some challenges for how to securely issue new certificates. You need to make sure that the certificate authority's private key is not compromised and the certificate authority needs some way to authenticate that the entity requesting a new host certificate has the right to do so.
Unfortunately, there is no easy solution to this problem. The general form of this problem (not specific to SSH) is called "Secure Introduction", and describes the challenges of securely issuing a new entity its first credential, from which others can then be derived.
This is not a problem that Terraform is equipped to solve on its own, and so teams with this security requirement tend to deploy specialized software for this purpose, such as HashiCorp Vault which allows using facilities provided by your cloud platform (AWS) to help issue initial credentials to a new VM.