Pular para o conteúdo principal

Virtual Machine IaC

Podemos utilizar o Terraform e várias outras linguagens para criar uma máquina virtual.

# Provedor Azure
# Nesse caso estamos usando as credenciais da conta que está logada
# Não estamos nos importando onde está o state file.
provider "azurerm" {
features {}
}

variable "resource_group_name" {
description = "Nome do grupo de recursos"
type = string
default = "test-rg"
}

variable "location" {
description = "Região da Azure onde os recursos serão criados"
type = string
default = "eastus"
}

variable "vm_name" {
description = "Nome da máquina virtual"
type = string
default = "test"
}

variable "vnet_name" {
description = "Nome da Virtual Network"
type = string
default = "test"
}

# Resource Group
resource "azurerm_resource_group" "rg" {
name = var.resource_group_name
location = var.location
}

# Virtual Network
resource "azurerm_virtual_network" "vnet" {
name = "${var.vnet_name}_vnet"
# Poderíamos usar a variável, mas se você pode pegar do grupo de recursos é sempre melhor, evita erros
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
address_space = ["10.0.0.0/16"]
}

# Subnet
resource "azurerm_subnet" "subnet" {
name = "${var.vnet_name}_subnet"
resource_group_name = azurerm_resource_group.rg.name
virtual_network_name = azurerm_virtual_network.vnet.name
address_prefixes = ["10.0.1.0/24"]
}

# Uma VM precisa de uma interface de rede
resource "azurerm_network_interface" "nic" {
name = "${var.vm_name}_nic"
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name

ip_configuration {
name = "configuracao-ip"
subnet_id = azurerm_subnet.subnet.id
private_ip_address_allocation = "Dynamic" # Qualquer IP da subnet acima
}
}

# VM
resource "azurerm_virtual_machine" "vm" {
name = "${var.vm_name}_vm"
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
network_interface_ids = [azurerm_network_interface.nic.id]
vm_size = "Standard_D2pls_v5"

storage_os_disk {
name = "minha-osdisk"
caching = "ReadWrite"
create_option = "FromImage"
managed_disk_type = "Standard_LRS"
}

storage_image_reference {
publisher = "Canonical"
offer = "ubuntu-24_04-lts"
sku = "server-arm64"
version = "latest"
}

os_profile {
computer_name = "${var.vm_name}"
admin_username = "adminuser"
admin_password = "SenhaSuperSegura123"
}

os_profile_linux_config {
disable_password_authentication = false
}
}

# Saída
output "endereco_ip" {
value = azurerm_network_interface.nic.private_ip_address
}