Thursday, September 3, 2020

Spin up virtual machine pre configured with WinRM access over https in Azure using Terraforms

Note: Basic knowledge of Terraforms is required.

If you are creating a VM in Azure and you want WinRM to be preconfigured for access over https and a certificate automatically created and linked with VM DNS see following steps.

Step 1: Download VM Terraforms sample from Github

You can download Terraforms sample from here and save it as e.g. (i needed one with the SQL):

Make sure to setup up the domain label, where var.dnsName is variable which you can declare in

domain_name_label = "${var.dnsName}winsqlhost"

Step 2: Add provisioner remote-exec:

To configure WinRM you need to add provisioner "remote-exec" to your Terraform, which triggers automatically once VM has spun up in the cloud.

resource "null_resource" "main" {
  triggers = {
    "after" = azurerm_mssql_virtual_machine.main.virtual_machine_id

  provisioner "remote-exec" {
    connection {

      type     = "winrm"
      user     = var.username
      password = var.pass
      https    = true
      insecure = true
      port     = 5986
      use_ntlm = true
      host     = "${var.dnsName}"


If you need to connect via http you don't need Step 3.

Step 3: Configure Key vault & Certificate with DSN name:

If VM is not on the domain and you need to connect through local machine you will have to setup Certificate for WinRM https access.

Download sample Terraform from here and save as e.g. (Generating a new certificate example)

Provide dns_names and CN equals to our DNS Name
     subject_alternative_names {
        dns_names = ["${var.dnsName}"""]

      subject            = "CN=${var.dnsName}"
      validity_in_months = 12

Link certificate with your VM in as follows:
  os_profile_secrets {
    source_vault_id =
    vault_certificates {
      certificate_url   = azurerm_key_vault_certificate.main.secret_id
      certificate_store = "My"

Now when you run Terraform your VM will be preconfigured with WinRM and ready to connect, you can connect WinRM over https port:5986 using DNS name.

Happy IaC! 😊

No comments:

Post a Comment