使用 Terraform 在 Azure 上创建带有 VNet 的虚拟机 - CentOS 7
本指南将引导您使用 Terraform 在 Azure 上创建一个带有虚拟网络 (VNet) 的虚拟机。虚拟机将运行 CentOS 7 操作系统,并配置网络安全组 (NSG) 允许 SSH 连接。
以下代码将创建以下资源:
- 资源组
- 虚拟网络
- 子网
- 网络安全组
- 公共 IP 地址
- 网络接口
- 虚拟机
代码
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "example" {
name = "example-resource-group"
location = "eastus"
}
resource "azurerm_virtual_network" "example" {
name = "example-vnet"
address_space = ['192.168.10.0/24']
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
}
resource "azurerm_subnet" "example" {
name = "example-subnet"
resource_group_name = azurerm_resource_group.example.name
virtual_network_name = azurerm_virtual_network.example.name
address_prefixes = ['192.168.10.0/28']
}
resource "azurerm_network_security_group" "example" {
name = "vm-nsg"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
security_rule {
name = "allow_ssh"
priority = 1001
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "22"
source_address_prefix = "*"
destination_address_prefix = "*"
}
}
resource "azurerm_public_ip" "example" {
name = "example-pip"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
allocation_method = "Static"
tags = {
environment = "example"
}
}
resource "azurerm_network_interface" "example" {
name = "example-nic"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
ip_configuration {
name = "example-ipc"
subnet_id = azurerm_subnet.example.id
private_ip_address_allocation = "Static"
private_ip_address = "192.168.10.100"
public_ip_address_id = azurerm_public_ip.example.id
}
}
resource "azurerm_linux_virtual_machine" "example" {
name = "example-vm"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
size = "Standard_B2ms"
admin_username = "azureuser"
admin_password = "P@ssw0rd1234"
network_interface_ids = [
azurerm_network_interface.example.id,
]
os_disk {
name = "example-osdisk"
caching = "ReadWrite"
storage_account_type = "Standard_LRS"
}
source_image_reference {
publisher = "OpenLogic"
offer = "CentOS"
sku = "7.6"
version = "latest"
}
custom_data = <<EOF
#!/bin/bash
echo 'Hello, World!' > /tmp/hello.txt
EOF
}
配置说明
- 虚拟机的 IP 地址设置为 '192.168.10.100'。
- 虚拟网络的地址空间设置为 '192.168.10.0/24'。
- 子网的地址空间设置为 '192.168.10.0/28'。
- 网络安全组 (NSG) 允许 SSH 连接。
- 虚拟机使用 'Standard_B2ms' 大小。
- 虚拟机使用 'CentOS 7.6' 操作系统镜像。
- 虚拟机在创建时使用自定义数据来创建名为 '/tmp/hello.txt' 的文件。
执行代码
要执行代码,请使用以下命令:
terraform init
terraform apply
注意事项
- 请确保您的 Azure 订阅中具有足够的资源来创建虚拟机和相关资源。
- 密码 'P@ssw0rd1234' 仅用于演示目的。请在实际使用中使用更强的密码。
结论
使用 Terraform 在 Azure 上创建带有 VNet 的虚拟机非常简单。通过使用代码,您可以轻松地创建和管理您的 Azure 资源。
原文地址: https://www.cveoy.top/t/topic/mJZ9 著作权归作者所有。请勿转载和采集!