When provisioning Linux VMs in the cloud, it is useful to use SSH keys to bootstrap the VMs with some initial configuration. This post explains how to provision your VMs using a disposable SSH key.
Terraform helps by providing the
tls_private_key resource type.
In the terraform VM resource I configure the VM to use the public key. In this example, I’m using Azure so the resource would be an
azurerm_virtual_machine. The value of
path in the ssh_keys attribute must be set to the path of the admin user’s
authorized_hosts file. The
key_data is set to the
public_key_openssh attribute of the
bootstrap_private_key resource created above.
Any provisioners that need to connect to the remote host can then be configured to use the private key from the
In this case terraform copies across some bootstrap code onto the VM which provisions my user accounts. Finally, it deletes the admin user’s
authorized_keys file to ensure that the ephemeral key cannot be used to log in again.
Terraform will store the private key in the state file, and in the event that a VM resource is destroyed and re-created, the same key will be used to provision the resource. Of course, the state file should be stored securely anyway, but in an ideal world it would be possible to only define this resource for the duration of the
apply. Maybe some new features in terraform in the future will help with this.
It is possible to partially workaround this, by always tainting the
tls_private_key after an apply, which would guarantee that the key is recreated on the next