Ephemeral SSH Keys for EC2 Instances in Terraform

Terraform’s aws_key_pair resource requires an existing user-supplied key pair- it won’t create one for you. At first glance it would seem that leveraging this would require us to pre-generate a key pair outside of Terraform’s lifecycle, but we can do this natively with a bit of creative resource management.

Rather than generate an SSH key pair out of cycle, the tls_private_key resource can create an RSA key for us. We can then write it to disk and export the public key it to a format OpenSSH will like via the ssh-keygen utility. Once that’s done, we can read it back in as a data resource (taking care to depend on it) and add the AWS resource. Following all that, we can apply the key pair to instances, ASGs, etc:

Leave a Reply

Your email address will not be published. Required fields are marked *