Tls_private_key => get private key for use with tools putty or ansible

Hey, i am using tls_private_key to generate a private key for my virtual machines, thanks for that. But there is a problem: How can I get the key securely when running that plan in the terraform cloud? Locally i can output the private key to the console, but in the cloud i won’t do that.

So the question is how to get the private pem to connect to the created virtual machines later?

Kind regards,

Hi Sebastian,

If you declare an output value in your root module which exports the private key then you’ll be able to access that value as stored in the workspace state.

Since tls_private_key marks the private key attributes as sensitive, Terraform won’t allow you to export them as output values without explicitly declaring that you intend to make the sensitive values externally-accessible, by adding the sensitive = true argument:

output "private_key" {
  value     = tls_private_key.example.private_key_openssh
  sensitive = true

When you mark a root module output value as sensitive, you ask Terraform to avoid showing the value in cleartext in the main UI output, but the data is still available to anyone who can directly retrieve the state, and so you should be careful to constrain who has such access.

If you are using Terraform CLI to drive Terraform Cloud remote operations then you can retrieve the raw sensitive value in cleartext, and redirect it to a file on disk for use with other software, using the -raw option on terraform output:

terraform output -raw private_key >private_key.pem

For this to work, you’ll need to have already configured a Terraform Cloud API token that has sufficient access to retrieve the state for the currently-selected workspace.