Files
les-03/opdracht-1/main.tf
2025-05-27 18:57:23 +00:00

119 lines
3.3 KiB
HCL

variable "azure_private_key_path" {
default = "/home/student/.ssh/azure"
}
data "local_file" "azure_private_key" {
filename = var.azure_private_key_path
}
# Azure
resource "azurerm_virtual_network" "main" {
name = "${var.prefix}-network"
address_space = ["10.0.0.0/16"]
location = var.azure_location
resource_group_name = var.azure_resourcegroup
}
resource "azurerm_subnet" "main" {
name = "internal"
resource_group_name = var.azure_resourcegroup
virtual_network_name = azurerm_virtual_network.main.name
address_prefixes = ["10.0.2.0/24"]
}
resource "azurerm_public_ip" "pip" {
name = "${var.prefix}-pip"
resource_group_name = var.azure_resourcegroup
location = var.azure_location
allocation_method = "Static"
}
resource "azurerm_network_interface" "main" {
name = "${var.prefix}-nic"
location = var.azure_location
resource_group_name = var.azure_resourcegroup
ip_configuration {
name = "internal"
subnet_id = azurerm_subnet.main.id
private_ip_address_allocation = "Dynamic"
public_ip_address_id = azurerm_public_ip.pip.id
}
}
resource "azurerm_network_security_group" "main" {
name = "${var.prefix}-nsg"
location = var.azure_location
resource_group_name = var.azure_resourcegroup
security_rule {
access = "Allow"
direction = "Inbound"
name = "tls"
priority = 100
protocol = "Tcp"
source_port_range = "*"
source_address_prefix = "*"
destination_port_range = "22"
destination_address_prefix = azurerm_network_interface.main.private_ip_address
}
}
resource "azurerm_network_interface_security_group_association" "main" {
network_interface_id = azurerm_network_interface.main.id
network_security_group_id = azurerm_network_security_group.main.id
}
# Render userdata template with skylab SSH key
data "template_file" "azure_cloudinit" {
template = file("${path.module}/cloudinit-azure.yaml")
vars = {
azure-ssh-key = trimspace(data.azurerm_ssh_public_key.azure.public_key)
}
}
resource "azurerm_linux_virtual_machine" "main" {
name = "${var.prefix}-vm"
location = var.azure_location
resource_group_name = var.azure_resourcegroup
network_interface_ids = [
azurerm_network_interface.main.id,
]
size = "Standard_B2ats_v2"
admin_username = "adminuser"
admin_ssh_key {
username = "adminuser"
public_key = data.azurerm_ssh_public_key.azure.public_key
}
custom_data = base64encode(data.template_file.azure_cloudinit.rendered)
os_disk {
caching = "ReadWrite"
storage_account_type = "Standard_LRS"
}
source_image_reference {
publisher = "Canonical"
offer = "ubuntu-24_04-lts"
sku = "server"
version = "latest"
}
}
locals {
inventory_content = templatefile("${path.module}/ansible-inventory.tmpl", {
ip = azurerm_linux_virtual_machine.main.public_ip_address })
}
resource "local_file" "ansible_inventory" {
content = local.inventory_content
filename = "${path.module}/inventory.ini"
}
output "ip_addresses" {
value = local_file.ansible_inventory.content
}