Terraform Azure_Linux_VM makes SSH key not work

Viewed 328

How do I ssh into my newly created Azure_VM via SSH?

I am setting up a simple VM via Terraform, assigning it a public IP and an SSH key which I have locally. Using the tutorial from the terraform page itself: https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/linux_virtual_machine

resource "azurerm_linux_virtual_machine" "example" {
...
  admin_username = "adminuser"

  admin_ssh_key {
    username   = "adminuser"
    public_key = file("~/.ssh/id_rsa.pub")
  }

[...]
}

However, after Terraform has created the machine, I can not log into the machine.

$ ssh adminuser@xxx.xxx.xxx.xxx yields:

adminuser@137.117.168.115: Permission denied (publickey).

Tried: First I thought it was the wrong public key. So I checked the public_key on the machine with:

az vm list --query "[].{SSH: 
osProfile.linuxConfiguration.ssh.publicKeys[].keyData}" -o json

and compared it to my public key on my local machine. They are the same, except for ONE "\n" that is printed in the Azure-VM output. Adding a new line to my local public key however did not fix the issue.

The Catch: Sometimes, after destroying the machine and rebulding it I can login. After and additional terraform destroy and terraform apply it doesn't work anymore. I don t get what I am doing wrong

So, how do I get to SSH into my newly created VM?

1 Answers

Turns out I did overwrite the default (adminuser) with a cloud_init config. After adding the default user to the cloud_config I could connect via SSH to adminuser@xxx.xxx.xxx.xxx

 data "template_cloudinit_config" "config" {                                     
   gzip = true                                                                   
   base64_encode = true                                                          
                                                                                 
   part {                                                                        
     content_type = "text/cloud-config"                                          
     content      = "users: [default, foobar, barfoo]"
   }                                                                             
 }                                                                               
    
Related