在使用Terraform创建Azure Linux虚拟机时,可以使用Terraform的变量来动态地定义资源的属性。以下是一个示例解决方案,其中包含了Terraform变量和Azure Linux虚拟机的Terraform代码示例。
variable "resource_group_name" {
description = "Name of the resource group"
type = string
}
variable "location" {
description = "Azure region where the resources will be created"
type = string
default = "eastus"
}
variable "vm_name" {
description = "Name of the virtual machine"
type = string
}
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "example" {
name = var.resource_group_name
location = var.location
}
resource "azurerm_linux_virtual_machine" "example" {
name = var.vm_name
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
size = "Standard_DS2_v2"
admin_username = "adminuser"
admin_ssh_key {
username = "adminuser"
public_key = file("~/.ssh/id_rsa.pub")
}
os_disk {
name = "osdisk"
caching = "ReadWrite"
storage_account_type = "Premium_LRS"
disk_size_gb = 30
}
source_image_reference {
publisher = "Canonical"
offer = "UbuntuServer"
sku = "18.04-LTS"
version = "latest"
}
network_interface {
name = "nic"
primary = true
network_security_group_id = azurerm_network_security_group.example.id
ip_configuration {
name = "config"
subnet_id = azurerm_subnet.example.id
}
}
}
resource "azurerm_network_security_group" "example" {
name = "nsg"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
security_rule {
name = "SSH"
priority = 1001
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "22"
source_address_prefix = "*"
destination_address_prefix = "*"
}
}
resource "azurerm_subnet" "example" {
name = "subnet"
resource_group_name = azurerm_resource_group.example.name
virtual_network_name = azurerm_virtual_network.example.name
address_prefixes = ["10.0.1.0/24"]
}
resource "azurerm_virtual_network" "example" {
name = "vnet"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
address_space = ["10.0.0.0/16"]
}
resource_group_name = "my-resource-group"
vm_name = "my-vm"
terraform init
terraform plan
terraform apply
上述示例代码演示了如何使用Terraform变量在Azure中创建Linux虚拟机。可以根据需要自定义变量的值,并使用Terraform命令来创建虚拟机。