So far we have created resources with individual CLI commands: a resource group, a network, an NSG with its rules, a VPN... It works, but it raises uncomfortable questions. What happens if it has to be repeated in another region for disaster recovery? How does Laura know, six months from now, whether somebody changed an NSG rule from the portal? How does Marc review what Laura is about to deploy before she deploys it? Infrastructure as Code (IaC) answers all of this: describing the infrastructure in text files that are stored in a repository, reviewed like any other code, and applied with a tool that takes care of creating, modifying, or destroying the resources so they match what is described. In this lesson you will understand why IaC is the professional way of working with IaaS, the difference between the declarative and the imperative approach, the main tools, and you will build step by step, with Terraform, the ERP test environment for Hortalia that we planned in the previous lesson.
- Why Infrastructure as Code
| Problem when working "by hand" (portal or individual commands) | How IaC solves it |
|---|---|
| Every environment ends up slightly different ("it worked in test") | Repeatability: the same code creates identical environments |
| Nobody knows who changed what or why | Version control: every change is a commit in Git with an author, a date, and a reason |
| Changes are applied without anyone reviewing them | Review: changes are proposed as a pull request and another person approves them |
| Someone changes something from the portal and nobody finds out | Drift detection: the tool compares what is real with what is described and reports the differences |
| The documentation is out of date | The code is the documentation: it describes exactly what exists |
| Recovering an environment after a disaster takes days | Fast recreation: the same code is applied in another region |
| Test resources are left forgotten | Clean destruction: one command removes everything the code created |
Configuration drift deserves an explanation: it is the difference that builds up between how the infrastructure should be and how it really is, because of manual changes, emergencies, or mistakes. It is silent and dangerous: one day somebody opens port 3389 to the internet "for a quick test" and nobody closes it. With IaC, every plan run detects that difference.
- Declarative versus imperative
- Imperative: you describe the steps to reach the result. "Create the group; then create the network; then add this rule". That is what we did with
azin 02-02. If you run it twice, it may fail (the resource already exists) or create duplicates. - Declarative: you describe the desired final state. "There must be a group with this name, a network with this range, and an NSG with these rules". The tool works out what steps are needed. If you run it twice, the second time it does nothing because everything is already as it should be (it is idempotent).
Compare the same NSG rule in both styles:
# Imperative (CLI): an order that gets executed
az network nsg rule create --resource-group rg-hortalia-erp-pruebas \
--nsg-name nsg-snet-erp-pruebas --name Permitir-RDP-Almacen \
--priority 110 --direction Inbound --access Allow --protocol Tcp \
--source-address-prefixes 192.168.10.0/24 --destination-port-ranges 3389# Declarative (Terraform): a description of what must exist
security_rule {
name = "Permitir-RDP-Almacen"
priority = 110
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_address_prefix = "192.168.10.0/24"
source_port_range = "*"
destination_address_prefix = "*"
destination_port_range = "3389"
}The practical difference shows up when something changes. If tomorrow the warehouse network becomes 192.168.20.0/24, in the declarative style it is enough to change the value and apply again: the tool detects that the rule exists with a different value and updates it. In the imperative style you would have to write a new update command and remember to run it in every environment.
- IaC tools
| Tool | Approach | Providers | Language | State | Comment |
|---|---|---|---|---|---|
| Terraform (HashiCorp, now part of IBM) | Declarative | Multi-provider (thousands of providers) | HCL | A state file managed by the user | The de facto standard; since 2023 under the BSL license (not open source) |
| OpenTofu (Linux Foundation) | Declarative | Multi-provider, compatible with Terraform providers | HCL | Same as Terraform | An open fork (MPL license) of Terraform; almost identical commands (tofu instead of terraform) |
| Bicep / ARM templates | Declarative | Azure only | Bicep (compiles to ARM JSON) | Managed by Azure | Very well integrated and with immediate support for Azure news |
| AWS CloudFormation | Declarative | AWS only | YAML / JSON | Managed by AWS | Native to AWS; the CDK lets you write it in programming languages |
| Pulumi | Declarative (with programming languages) | Multi-provider | Python, TypeScript, Go, C#, Java | Pulumi Cloud or your own storage | Useful for development teams that prefer their usual language |
| Ansible | Mainly procedural | Multi-provider | YAML (playbooks) | Stateless | It shines at configuring the inside of machines (installing software, OS settings) rather than at creating infrastructure |
In practice, it is common to combine a provisioning tool (Terraform, OpenTofu, Bicep) to create the infrastructure with a configuration one (Ansible, PowerShell DSC, start-up scripts) to prepare the inside of the VMs. Google Cloud, for its part, offers Infrastructure Manager, which runs Terraform configurations as a managed service.
Laura chooses Terraform (compatible with OpenTofu) for a strategic reason: being multi-provider, what she learns will serve her if in module 5 Hortalia chooses another provider or combines several, and the same workflow will serve for the networks, the VM, and the backups.
- A complete example: the ERP test environment in Terraform
We are going to create the test environment planned in IaaS Use Cases: a resource group, a 10.30.0.0/16 network with a subnet, an NSG that only allows RDP and SQL from the warehouse, a network interface with a fixed private IP, the vm-erp-pruebas VM (Windows Server 2022 with SQL Server 2022 Developer), and a data disk.
Cost warning: applying this code creates resources that are billed (a Windows VM and two disks). If you try it out, destroy it afterwards with
terraform destroy. To practise without the cost of a Windows license, you can adapt the exercise in the next lesson, which uses a small Linux VM.
Terraform reads all the .tf files in a folder as if they were one. For clarity, we split them up like this:
erp-pruebas/ ├── versions.tf # Terraform version, provider, and backend ├── variables.tf # input parameters ├── main.tf # the resources ├── outputs.tf # values shown at the end └── terraform.tfvars # specific values for the variables (no secrets)
4.1 versions.tf: versions and provider
terraform {
required_version = ">= 1.9"
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "~> 4.0"
}
}
}
provider "azurerm" {
features {}
subscription_id = var.subscription_id
}- The
terraform { ... }block configures the tool itself.required_versiondemands a minimum version of Terraform to avoid incompatibilities between people on the team. required_providersdeclares the providers: the plugins that know how to talk to each platform's API.hashicorp/azurermis the Azure one.version = "~> 4.0"accepts any 4.x version, but not 5.0, which could bring breaking changes.- The
provider "azurerm"block configures the connection.features {}is mandatory even when empty (it allows advanced behaviours to be tuned).subscription_idsays which Azure subscription to work in; in version 4 of the provider it must be stated. Authentication is taken, by default, from the session opened withaz login.
4.2 variables.tf: input parameters
variable "subscription_id" {
description = "ID of the Azure subscription"
type = string
}
variable "location" {
description = "Azure region"
type = string
default = "spaincentral"
}
variable "network_range" {
description = "Address space of the test network"
type = string
default = "10.30.0.0/16"
}
variable "subnet_range" {
description = "Range of the test ERP subnet"
type = string
default = "10.30.1.0/24"
}
variable "warehouse_network" {
description = "Warehouse network, which arrives over the VPN"
type = string
default = "192.168.10.0/24"
}
variable "vm_size" {
description = "Size of the test VM"
type = string
default = "Standard_D2s_v5"
}
variable "admin_username" {
description = "Local administrator user of the VM"
type = string
default = "laura"
}
variable "admin_password" {
description = "Local administrator password (never in the repository)"
type = string
sensitive = true
validation {
condition = length(var.admin_password) >= 14
error_message = "The password must be at least 14 characters long."
}
}- Each
variableblock defines a parameter with a description (documentation), a type (string,number,bool,list...) and, optionally, a default value. - Variables with no
default(subscription_id,admin_password) are mandatory: if they are not supplied, Terraform asks for them. sensitive = truesays that the value is secret: Terraform will not show it on screen or in theplanoutput.validationadds a check of your own: if the password is shorter than 14 characters, Terraform stops with the given message before touching anything.- Thanks to the variables, the same code serves for the disaster recovery in 02-04: it would be enough to set
location = "francecentral"and another network range.
4.3 main.tf: the resources
locals {
tags = {
proyecto = "erp"
entorno = "pruebas"
propietario = "laura"
horario = "laboral"
gestionado_por = "terraform"
}
}
resource "azurerm_resource_group" "test" {
name = "rg-hortalia-erp-pruebas"
location = var.location
tags = local.tags
}
resource "azurerm_virtual_network" "test" {
name = "vnet-hortalia-pruebas"
location = azurerm_resource_group.test.location
resource_group_name = azurerm_resource_group.test.name
address_space = [var.network_range]
tags = local.tags
}
resource "azurerm_subnet" "erp" {
name = "snet-erp-pruebas"
resource_group_name = azurerm_resource_group.test.name
virtual_network_name = azurerm_virtual_network.test.name
address_prefixes = [var.subnet_range]
}localsdefines reusable local values. Here, the map of tags that every resource will carry. Notehorario = "laboral": it is the tag the start and stop script from 02-04 looks for, so the VM will automatically be covered by the schedule.- Each
resource "TYPE" "LOCAL_NAME"block describes a resource. The type (azurerm_resource_group) is defined by the provider; the local name (test) only serves to refer to it inside the code. The real name in Azure is thenameattribute. azurerm_resource_group.test.locationis a reference: "the location of the resource group defined above". References have an important effect: Terraform infers from them the order of creation (first the group, then the network, then the subnet) without you having to state it.address_spaceandaddress_prefixesare lists (in square brackets) because a network or a subnet can have several ranges.- Subnets do not accept tags in Azure, which is why
azurerm_subnethas notags.
resource "azurerm_network_security_group" "erp" {
name = "nsg-snet-erp-pruebas"
location = azurerm_resource_group.test.location
resource_group_name = azurerm_resource_group.test.name
tags = local.tags
security_rule {
name = "Permitir-SQL-Almacen"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_address_prefix = var.warehouse_network
source_port_range = "*"
destination_address_prefix = "*"
destination_port_range = "1433"
}
security_rule {
name = "Permitir-RDP-Almacen"
priority = 110
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_address_prefix = var.warehouse_network
source_port_range = "*"
destination_address_prefix = "*"
destination_port_range = "3389"
}
security_rule {
name = "Denegar-Resto-VNet"
priority = 4000
direction = "Inbound"
access = "Deny"
protocol = "*"
source_address_prefix = "VirtualNetwork"
source_port_range = "*"
destination_address_prefix = "*"
destination_port_range = "*"
}
}
resource "azurerm_subnet_network_security_group_association" "erp" {
subnet_id = azurerm_subnet.erp.id
network_security_group_id = azurerm_network_security_group.erp.id
}- The NSG includes its rules as nested
security_ruleblocks, with the same fields we saw in the CLI in 02-02: priority, direction, access, protocol, source, and destination port. - The third rule overrides the default
AllowVnetInBoundrule, as we explained in 02-02. azurerm_subnet_network_security_group_associationassociates the NSG with the subnet. In Terraform, as in the CLI, it is an explicit step you should not forget..idis the resource's full identifier in Azure, which Terraform knows once it has been created.
resource "azurerm_network_interface" "vm" {
name = "nic-vm-erp-pruebas"
location = azurerm_resource_group.test.location
resource_group_name = azurerm_resource_group.test.name
tags = local.tags
ip_configuration {
name = "internal"
subnet_id = azurerm_subnet.erp.id
private_ip_address_allocation = "Static"
private_ip_address = "10.30.1.10"
}
}
resource "azurerm_windows_virtual_machine" "erp" {
name = "vm-erp-pruebas"
location = azurerm_resource_group.test.location
resource_group_name = azurerm_resource_group.test.name
size = var.vm_size
admin_username = var.admin_username
admin_password = var.admin_password
network_interface_ids = [azurerm_network_interface.vm.id]
timezone = "Romance Standard Time"
tags = local.tags
os_disk {
name = "osdisk-vm-erp-pruebas"
caching = "ReadWrite"
storage_account_type = "StandardSSD_LRS"
disk_size_gb = 128
}
source_image_reference {
publisher = "MicrosoftSQLServer"
offer = "sql2022-ws2022"
sku = "sqldev-gen2"
version = "latest"
}
}
resource "azurerm_managed_disk" "data" {
name = "disk-vm-erp-pruebas-datos"
location = azurerm_resource_group.test.location
resource_group_name = azurerm_resource_group.test.name
storage_account_type = "StandardSSD_LRS"
create_option = "Empty"
disk_size_gb = 128
tags = local.tags
}
resource "azurerm_virtual_machine_data_disk_attachment" "data" {
managed_disk_id = azurerm_managed_disk.data.id
virtual_machine_id = azurerm_windows_virtual_machine.erp.id
lun = 0
caching = "ReadOnly"
}- Network interface (
azurerm_network_interface): connects the VM to the subnet. Inip_configuration,private_ip_address_allocation = "Static"withprivate_ip_address = "10.30.1.10"pins the private IP, so it does not change when the VM is deallocated. There is no public IP: the VM will only be reachable from the private network. - VM (
azurerm_windows_virtual_machine):name: on Windows it is also the computer name, which cannot be longer than 15 characters (vm-erp-pruebashas 14).size,admin_username,admin_password: take their values from the variables. The password never appears written in the code.network_interface_ids: a list of interfaces; the VM uses the one created above.timezone = "Romance Standard Time": the Windows time zone for Madrid, so that the ERP logs carry the local time.os_disk: the operating system disk.caching = "ReadWrite"is the usual setting for the system disk;StandardSSD_LRSis a standard SSD with local redundancy (enough for testing; production would use Premium).source_image_reference: the image, with the four parts of the URN we saw in 02-01. Thesqldev-gen2SKU includes SQL Server 2022 Developer, with no SQL license cost for testing.
- Data disk (
azurerm_managed_disk): an empty disk (create_option = "Empty") of 128 GB for the test databases. - Disk attachment (
azurerm_virtual_machine_data_disk_attachment): attaches it to the VM on LUN 0 (the disk's "slot" number on the VM).caching = "ReadOnly"is the usual recommendation for SQL Server data disks.
For the warehouse to reach this network, it will have to be peered (VNet peering) with vnet-hortalia-spaincentral and allowed to use its VPN Gateway (what Azure calls "gateway transit"). We leave that out of the example to focus on the essentials.
4.4 outputs.tf and terraform.tfvars
output "vm_private_ip" {
description = "Private IP of the ERP test VM"
value = azurerm_network_interface.vm.private_ip_address
}
output "vm_id" {
description = "Identifier of the VM in Azure"
value = azurerm_windows_virtual_machine.erp.id
}# terraform.tfvars - specific values (no secrets)
subscription_id = "00000000-0000-0000-0000-000000000000"
vm_size = "Standard_D2s_v5"- The
outputblocks show useful information at the end and allow other configurations to reuse it. terraform.tfvarsassigns values to the variables; Terraform loads it automatically. The subscription identifier in the example is fictional. The password does not appear here: it is passed through an environment variable, as we will see in section 6.
- The workflow: init, plan, apply, and destroy
flowchart LR
W["Write / modify<br/>.tf files"] --> I["terraform init<br/>(once, or when changing<br/>providers or backend)"]
I --> P["terraform plan<br/>what is going to change?"]
P --> R{"Reviewed<br/>and correct?"}
R -->|No| W
R -->|Yes| A["terraform apply<br/>apply the changes"]
A --> W
A -.-> D["terraform destroy<br/>(when the environment is done)"]
5.1 terraform init
init prepares the folder: it downloads the azurerm provider into the hidden .terraform/ folder, creates the .terraform.lock.hcl file (which pins the exact provider versions and must be kept in Git) and configures the state backend. Abbreviated output:
Initializing the backend... Initializing provider plugins... - Finding hashicorp/azurerm versions matching "~> 4.0"... - Installing hashicorp/azurerm v4.x.x... Terraform has been successfully initialized!
5.2 terraform plan
export TF_VAR_admin_password=...: Terraform automatically reads any environment variable starting withTF_VAR_as the value of the variable with the same name. That way the password is not left in any file (in a real environment, you would fetch it from a secrets manager instead of typing it).terraform plan: compares the code with what exists and shows what it would do, without changing anything.-out=plan.tfplansaves the plan so exactly that can be applied later.
Abbreviated output:
Terraform will perform the following actions:
# azurerm_network_interface.vm will be created
+ resource "azurerm_network_interface" "vm" {
+ name = "nic-vm-erp-pruebas"
+ private_ip_address = "10.30.1.10"
...
}
# azurerm_windows_virtual_machine.erp will be created
+ resource "azurerm_windows_virtual_machine" "erp" {
+ admin_password = (sensitive value)
+ name = "vm-erp-pruebas"
+ size = "Standard_D2s_v5"
...
}
Plan: 9 to add, 0 to change, 0 to destroy.- The
+symbol means create; you will also see~(modify without recreating),-(destroy), and-/+(destroy and recreate, be careful with this one in production: changing a VM's image, for example, recreates it). (sensitive value): the password is not shown, thanks tosensitive = true.- The last line is the summary: 9 new resources (group, network, subnet, NSG, association, interface, VM, disk, and disk attachment).
Reading the plan carefully is the most important practice in IaC. It is what Laura will attach to every proposed change so that another person can review it.
5.3 terraform apply
It applies exactly the saved plan. Terraform creates the resources in the right order (and in parallel where they do not depend on each other) and finishes with:
Apply complete! Resources: 9 added, 0 changed, 0 destroyed. Outputs: vm_id = "/subscriptions/0000.../resourceGroups/rg-hortalia-erp-pruebas/providers/Microsoft.Compute/virtualMachines/vm-erp-pruebas" vm_private_ip = "10.30.1.10"
If someone now added a rule from the portal opening RDP to the internet, the next terraform plan would show ~ resource "azurerm_network_security_group" "erp" with the stray rule marked with -: Terraform has detected the drift and proposes removing it to get back to what the code describes.
5.4 terraform destroy
It shows a destruction plan (Plan: 0 to add, 0 to change, 9 to destroy.), asks for confirmation by typing yes, and removes only the resources this configuration manages. It is the clean way to finish a temporary environment or a disaster recovery drill.
With OpenTofu, the commands are the same, replacing terraform with tofu (tofu init, tofu plan...).
- State and secrets
6.1 What the state is
Terraform keeps in a file, terraform.tfstate, the mapping between each resource in the code and the real resource in Azure (its identifier and its attributes). Without it, it would not know which resources it created and could not work out differences. Three important things:
- The state contains secrets in plain text. Even though the password is marked as
sensitiveon screen, it is stored as it is in the state. It must never be pushed to Git. - If it is lost, Terraform "forgets" the infrastructure, which still exists but is no longer managed (it would have to be imported resource by resource).
- If two people apply at the same time with different copies of the state, they can corrupt it.
6.2 Remote backend
The solution is to keep the state in a remote backend, shared, encrypted, and with locking. In Azure, a storage account:
terraform {
backend "azurerm" {
resource_group_name = "rg-hortalia-tfstate"
storage_account_name = "sthortaliatfstate"
container_name = "tfstate"
key = "erp-pruebas.tfstate"
use_azuread_auth = true
}
}- This block goes inside the
terraform { }block inversions.tf. resource_group_name,storage_account_name,container_name: where the state is kept. This account is created once, by hand or with the CLI, before anything else (it is the chicken-and-egg problem: the state cannot be stored in something that does not yet exist).key: the name of the state file. Each environment (test, production, recovery) has its own, so that a mistake in one does not affect the others.use_azuread_auth = true: access is with the user's Entra ID identity, without storage account keys.- Azure locks the file (through a "lease" on the blob) while somebody is applying changes, preventing simultaneous runs.
Laura configures the sthortaliatfstate account with blob versioning (to recover an earlier state if it gets damaged), with no public access, and with permissions only for her and the identity that runs Terraform.
6.3 Secrets: what must never be in the repository
Laura creates a .gitignore file in the project folder:
# Folder of downloaded providers .terraform/ # State and state backups: they contain secrets *.tfstate *.tfstate.* # Saved plans: they can contain secrets too *.tfplan # Variable files with secrets (if anyone creates them) *.secret.tfvars crash.log
And she follows these rules:
- Passwords, keys, and certificates never in versioned
.tfor.tfvarsfiles: they go in environment variables or, better, in a secrets manager (Azure Key Vault, AWS Secrets Manager, Google Secret Manager), from which Terraform can read them. - Remember that, even so, they will end up in the state: that is why the state is protected like any other secret.
.terraform.lock.hclis versioned: it guarantees that everyone uses the same provider versions.
- Configuring the VM at start-up: cloud-init and scripts
Terraform creates the VM, but it does not install anything inside. For the initial configuration of the operating system there are two common mechanisms:
- cloud-init (Linux): a standard that almost every Linux cloud image runs on first boot. It is given a YAML file with packages to install, users, files, and commands. In Terraform, through the
custom_dataargument ofazurerm_linux_virtual_machine. We will use it in the hands-on exercise. - Extensions and scripts (Windows): in Azure, the Custom Script extension runs a PowerShell script inside the VM after creating it.
As an example, Laura adds to her configuration an extension that initialises and formats the data disk of vm-erp-pruebas with the settings recommended for SQL Server:
locals {
disk_script = <<-EOT
Get-Disk | Where-Object PartitionStyle -eq 'RAW' |
Initialize-Disk -PartitionStyle GPT -PassThru |
New-Partition -DriveLetter F -UseMaximumSize |
Format-Volume -FileSystem NTFS -NewFileSystemLabel 'SQLData' -AllocationUnitSize 65536 -Confirm:$false
EOT
}
resource "azurerm_virtual_machine_extension" "data_disk" {
name = "initialize-data-disk"
virtual_machine_id = azurerm_windows_virtual_machine.erp.id
publisher = "Microsoft.Compute"
type = "CustomScriptExtension"
type_handler_version = "1.10"
protected_settings = jsonencode({
commandToExecute = "powershell -ExecutionPolicy Bypass -EncodedCommand ${textencodebase64(local.disk_script, "UTF-16LE")}"
})
depends_on = [azurerm_virtual_machine_data_disk_attachment.data]
}<<-EOT ... EOTis a multi-line text block (heredoc); the hyphen allows it to be indented.- The PowerShell script looks for uninitialised disks (
PartitionStyle -eq 'RAW'), initialises them with a GPT partition table, creates a partition that takes up the whole disk with the letterF:, and formats it as NTFS with 64 KB allocation units, the usual recommendation for SQL Server data files. azurerm_virtual_machine_extension: installs the Custom Script extension (publisher,type, andtype_handler_versionidentify it) on the VM.protected_settings: configuration that Azure stores encrypted.jsonencodeturns the object into JSON.textencodebase64(..., "UTF-16LE")encodes the script in Base64 with the encodingpowershell -EncodedCommandexpects, which avoids every quoting and line-break problem when passing it as a command.depends_on: an explicit dependency. The script must not run until the disk is attached, and since there is no direct reference between the two resources, it has to be stated.
With this block, the next plan would show Plan: 1 to add, 0 to change, 0 to destroy.
For richer configurations maintained over time (installing the ERP, tuning SQL Server, applying security baselines), Laura will consider Ansible or PowerShell DSC, or building a custom image ready to go, as we saw in 02-01.
- Good practices
-
Every change goes through Git. A branch, a pull request with the
terraform planoutput attached, review by another person and, afterwards,apply. No changes from the portal in environments managed with IaC; if there is an emergency, it is reflected in the code immediately afterwards. -
Modules so you do not repeat yourself. A module is a folder of reusable Terraform code with its own variables. Laura can create an
erp-networkmodule and use it in production, test, and recovery:module "dr_network" { source = "./modules/erp-network" location = "francecentral" network_range = "10.21.0.0/16" warehouse_network = "192.168.10.0/24" }sourcesays where the module is and the rest are the values of its variables. Three environments, a single piece of code to maintain. -
Tags on everything. The
locals.tagsblock guarantees that every resource carries project, environment, owner, and who manages it. Sara will be able to see in Microsoft Cost Management exactly how much the ERP test environment costs, and the automation scripts (such as the schedule one) can rely on them. -
Naming convention. A prefix per resource type (
rg-,vnet-,snet-,nsg-,vm-,st...), project, and environment. It makes bills, logs, and the code itself easier to read. -
Pin the versions of Terraform and of the providers, and update them in a controlled way.
-
Format and validate:
terraform fmtapplies standard formatting to the code andterraform validatecatches syntax errors before theplan. -
One state per environment and a remote backend with locking and versioning.
-
Protect what cannot be recovered: for resources such as the backup account, the
lifecycle { prevent_destroy = true }block makes Terraform refuse to destroy them. -
Least privilege for Terraform too: the identity that applies changes in test should not be able to touch production.
Automating Terraform runs in continuous integration and deployment pipelines is the natural next step; we will see the concept of a pipeline, applied to applications, in the PaaS module.
Common Mistakes and Tips
- Pushing
terraform.tfstateor passwords to Git. The state contains secrets in the clear. Use.gitignore, a remote backend, and environment variables or secrets managers. - Applying without reading the plan. An unnoticed
-/+can recreate (and wipe) a production VM. Always read the plan and save it with-out. - Mixing manual changes and code. It creates drift and makes the next
applyundo other people's changes. If something was changed by hand, bring it into the code or import it. - A single state for everything. A mistake in test should not put production at risk. Separate states by environment.
- Forgetting implicit dependencies. If a resource needs another one to exist and there is no reference between them, use
depends_on. - Windows VM names longer than 15 characters. Azure will reject the computer name; shorten it or set
computer_nameseparately. - Not destroying test environments. If the environment is no longer needed,
terraform destroy; if it is just not needed overnight, deallocate the VM. - Tip: start small. Move to code first what is repeated most (the test environment) and expand from there. It is easier than trying to codify all your existing infrastructure in one go.
Exercises
Exercise 1. Change the code so that the size of the test VM is Standard_D4s_v5 just for a performance test, without touching main.tf. What would you change and what symbol would you expect to see in the plan for the VM?
Exercise 2. Add a rule to the NSG allowing RDP from the test Azure Bastion subnet 10.30.254.0/26 with priority 120. Write the security_rule block and explain what terraform plan would show.
Exercise 3. Marc reviews Laura's repository and finds these files: main.tf, variables.tf, .terraform.lock.hcl, terraform.tfstate, terraform.tfvars (with the subscription ID), and keys.secret.tfvars (with the password). Which ones should be in Git and which should not? What should Laura do immediately if the repository has already been shared?
Solutions
Solution 1. Change the value in terraform.tfvars (vm_size = "Standard_D4s_v5") or pass it when running: terraform plan -var="vm_size=Standard_D4s_v5" -out=plan.tfplan. In the plan, the VM would appear with ~ (in-place modification): ~ size = "Standard_D2s_v5" -> "Standard_D4s_v5", and the summary Plan: 0 to add, 1 to change, 0 to destroy. Azure will resize the VM, which means a restart. After the test, it is enough to put the previous value back and apply.
Common mistake: editing default in variables.tf for a temporary change. It works, but it changes the default value for everyone; for values of one specific environment you use .tfvars or -var.
Solution 2.
security_rule {
name = "Permitir-RDP-Bastion"
priority = 120
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_address_prefix = "10.30.254.0/26"
source_port_range = "*"
destination_address_prefix = "*"
destination_port_range = "3389"
}It is added inside the azurerm_network_security_group.erp resource. The plan would show ~ resource "azurerm_network_security_group" "erp" with the new rule marked with + inside the block, and the summary Plan: 0 to add, 1 to change, 0 to destroy. Priority 120 is lower than 4000, so the allow rule is evaluated before the general deny.
Solution 3. These must be in Git: main.tf, variables.tf, .terraform.lock.hcl, and terraform.tfvars (the subscription ID is not a secret in itself, although some organisations prefer not to publish it). These must not be: terraform.tfstate (it contains the password in the clear and every attribute of the resources) or keys.secret.tfvars. If the repository has already been shared: change the VM administrator password immediately (and any other exposed secret), remove those files from the repository and from its history (deleting them in a new commit is not enough, they are still in the earlier commits), migrate the state to a remote backend, and add the rules to .gitignore. Also review the VM's access logs in case somebody used the password.
Conclusion
Infrastructure as Code turns infrastructure into versioned, reviewable, repeatable text files that eliminate configuration drift and make it possible to recreate whole environments in minutes. You have seen the difference between the imperative approach (steps) and the declarative one (desired state), the main tools (Terraform/OpenTofu, Bicep, CloudFormation, Pulumi, and Ansible for configuration), and you have built Hortalia's ERP test environment with Terraform: resource group, network, subnet, NSG, interface with a fixed private IP, a Windows VM with SQL Server Developer, and a data disk, all with variables and tags. You have practised the init, plan, apply, and destroy cycle, you have learned why the state must live in a remote backend and why secrets never go into the repository, and you have configured the VM at start-up with a script extension.
The time has come to put it all into practice with your own hands. In the final lesson of the module, Hands-on Exercise: Setting Up a Virtual Machine, you will follow Laura through a guided exercise from start to finish: creating the network, the VM, connecting to it, adding a disk, installing software, taking a snapshot, deallocating it, and cleaning everything up at the end.
