SyntaxSage
SyntaxSage

Reputation: 357

Adding a ssh key to an GCP instance using terraform works but shows error on the console

I am adding ssh-keys to my gce instance using this:

ssh-keys  = "${var.ssh_user_name}:${var.ssh_pub_key}"

ssh_pub_key is the public key output variable of tls_private_key module which dynamically generates ssh-keys.

According to GCP ssh-key format , at the end of public key , user name should be appended but generating dynamic keys using tls_private_key resource will not add the user name

After adding the ssh-keys , I am able to login to gcp instance using the private key but if I try to edit on gcp console I get the following error:

"The SSH key is in the wrong format"

This is due to user name not being added at the end
My problem is :

ssh-keys  = "${var.ssh_user_name}:${var.ssh_pub_key}"

Shouldn't this be taking care of that? Is there another way to do this? If the ssh-key is really wrong then ssh shouldn't even be allowed . I have searched for all ways to add ssh-key at instance level in GCP through terraform, I am not able to find anything else

ssh-keys  = "${var.ssh_user_name}:${var.ssh_pub_key}"

The var.ssh_pub_key has extra \n line character at the end and I cannot modify this is the output variable of key generation module.

Upvotes: 1

Views: 2918

Answers (1)

Jakub Bujny
Jakub Bujny

Reputation: 4628

So user name is required in public key - not in private. So what about something simple like

"${var.ssh_user_name}:${var.ssh_pub_key} ${var.ssh_user_name}" - now terraform interpolation should make your public key in proper format

Edit: So solution for \n character at the end in pure terraform is:

locals {
  ssh_pub_key_without_new_line = "${replace(var.ssh_pub_key, "\n", "")}"
}

And then

"${var.ssh_user_name}:${local.ssh_pub_key_without_new_line} ${var.ssh_user_name}"

Upvotes: 2

Related Questions