通过 Terraform 创建 Azure Windows VM

Creating a Azure Windows VM through Terraform

在 Azure 中,我正在尝试使用 Terraform 创建 Windows VM。我之前使用 Template.json 文件通过 Powershell 完成了此操作。现在我必须处理 terraform,这是我完全陌生的。所以我搜索了一些在 Azure 中创建 VM 的示例脚本并找到了 this

在此 link 中,有一个示例 Terraform 脚本来旋转 Linux VM。但是我需要从图像中旋转一个 windows 虚拟机。我应该在哪里提供图像详细信息。我的完整要求是:

  1. 从映像创建 Windows VM(具有资源 ID)
  2. 我已经创建了资源组、虚拟网络、子网。我只需要传递这些值并创建它们。
  3. 我们已经从门户本身定义了子网地址前缀 Vnet 地址 space。那么我是否必须在脚本中再次给出或者我可以跳过它。
  4. 业务要求是任何虚拟机都不应具有 public IP 和 DNS 名称,因此如果我删除“# Create public IPs”部分,是否不会创建 public IP ?

创建Linux机器的脚本是here,我将其作为参考。

从 Terraform 的角度来看,Windows VM 与 Linux VM 非常相似。我认为第一大区别是 Windows VM 需要 os_profile_windows_config 属性,而 Linux VM 需要 os_profile_linux_config.

您在 Microsoft 站点上找到的 TF 代码是一个好的开始。此外,您可以查看 Terraform Registry. For example, here's a module for a Linux VM.

我强烈建议通读 VM resource 中的所有选项。我知道很多,但你应该明白你有什么选择。

最后,编写一些代码并对其进行测试是无可替代的。如果你做错了什么,Terraform and/or Azure API 会告诉你,如果不清楚,网络搜索会弹出答案或正确方向的指针。

下面是一个示例,说明如何使用数据来使用 terraform 中已有的资源,还有一个代码块来创建 windows VM。您将需要获取现有的 VNET 并创建 NIC

使用数据指令获取VNET azurerm_virtual_network,您可以看到下面的资源组语法。您需要将资源组和可能的位置添加到此块中。

使用 VNET ID 创建 azurerm_network_interface 资源

将网络接口 ID 添加到 VM (network_interface_ids = [])

Example TF Code to Create and load balance VMs

variable "subscription_id" {}
variable "client_id" {}
variable "client_secret" {}
variable "tenant_id" {}

provider "azurerm" {
  tenant_id       = "${var.tenant_id}"
  subscription_id = "${var.subscription_id}"
  client_id       = "${var.client_id}"
  client_secret   = "${var.client_secret}"
}

data "azurerm_resource_group" "resource_group" {
  name                = "learning-tf-web-rg"
}


resource "azurerm_virtual_machine" "web_server" {
  name                  = "server"
  location              = "westus2"
  resource_group_name   = "${data.azurerm_resource_group.resource_group.name}"
  network_interface_ids = []
  vm_size               = "Standard_B2s"

  storage_image_reference {
    publisher = "MicrosoftWindowsServer"
    offer     = "WindowsServer"
    sku       = "2016-Datacenter-Server-Core-smalldisk"
    version   = "latest"
  }

  storage_os_disk {
    name              = "server-os"
    caching           = "ReadWrite"
    create_option     = "FromImage"
    managed_disk_type = "Standard_LRS"
  }

  os_profile {
    computer_name      = "server"
    admin_username     = "server"
    admin_password     = "Passw0rd1234"

  }

  os_profile_windows_config {
  }

}