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. main.tf (i needed one with the SQL):
Make sure to setup up the domain label, where var.dnsName is variable which you can declare in variables.tf:
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}winsqlhost.westeurope.cloudapp.azure.com"
}
}
}
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. certificate.tf (Generating a new certificate example) https://www.terraform.io/docs/providers/azurerm/r/key_vault_certificate.html
Provide dns_names and CN equals to our DNS Name
subject_alternative_names {
dns_names = ["${var.dnsName}winsqlhost.westeurope.cloudapp.azure.com", "domain.hello.world"]
}
subject = "CN=${var.dnsName}winsqlhost.westeurope.cloudapp.azure.com"
validity_in_months = 12
Link certificate with your VM in main.tf as follows:
os_profile_secrets {
source_vault_id = azurerm_key_vault.main.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! 😊