How to change the admin password of a VM created using terraform

Zeinab Khosravi 40 Reputation points
2023-11-21T11:59:13.9633333+00:00

Hello everyone,

I have a VM on Azure that is created via Terraform, which was originally created with a static password as plain text. I want to change that to use a random string as the password, but that would try to re-create the VM entirely!

I have read a bit here: https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/reset-rdp#reset-by-using-the-vmaccess-extension-and-powershell and apparently you can use the VMAccessAgent extension to change the user's password without re-creating the VM. However, even after installing this extension on the VM with the new password value, the VM is still using the old password and doesn't respond to the new password! Is there any extra step I have to take to get this working? It is worth mentioning that I am using Bastion host to connect to the VM, and the VM uses windows OS.

Thank you very much in advance.

Azure Virtual Machines
Azure Virtual Machines
An Azure service that is used to provision Windows and Linux virtual machines.
7,252 questions
Azure
Azure
A cloud computing platform and infrastructure for building, deploying and managing applications and services through a worldwide network of Microsoft-managed datacenters.
993 questions
0 comments No comments
{count} votes

Accepted answer
  1. Luis Arias 5,126 Reputation points
    2023-11-21T13:28:02.5366667+00:00

    Hi Shadi, Sadly terraform always will try to recreate the machine when you change the password even if you already have the resource in your statefile the machine, a work around is using azure cli within terraform null resource as bellow exameple,:

    • Already have all definitions of VM
    • Null resource change the password based on variable new_value
    resource "null_resource" "reset_password" {
      triggers = {
        always_run = "${timestamp()}"
      }
      provisioner "local-exec" {
        command = "az vm user update --resource-group <RG-VM> --name <VM-NAME> --username <User-Name> --password newPassword01$"
      }
    }
    

    Note: that the local-exec provisioner will execute the command on the machine running Terraform, not on the VM. Therefore, you need to have the Azure CLI installed and configured on this machine

    Let Me know if this solve your challenge. Luis,

    Note: I recommend you protect sensitive variable as password in terraform (https://developer.hashicorp.com/terraform/tutorials/configuration-language/sensitive-variables)

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful