Course outlines for learning terraform.
expected time | requirements |
---|---|
30 minutes | A computer with Terraform installed. |
Goal: Learn how dependencies work in Terraform.
Terraform calculates dependencies by itself.
In this example it’s quite clear what needs to happen first and what second:
resource "azurerm_resource_group" "rg" {
name = "rg-robertdeboer-sbx"
location = "westeurope"
tags = {
costcenter = "infra"
solution = "terraform opleiding"
owner = "Robert de Bock"
environment = "sbx"
creationdate = "9/02/2021"
creator = "Robert de Bock"
}
}
# Create a virtual network
resource "azurerm_virtual_network" "vnet" {
name = "myTFVnet-robert"
address_space = ["10.0.0.0/16"]
location = "westeurope"
resource_group_name = azurerm_resource_group.rg.name
}
azurerm_resource_group
needs to be created.azurerm_virtual_network
refers to azurerm_resource_group.rg.name
, so this resource comes secondly.You can ask Terraform to show the dependencies using terraform graph
. To make an image, the binary dot
(in the package graphviz
) is required.
Sometimes Terraform can’t calculate the dependencies by itself and needs some help using the depends_on
argument, something like this:
# Many parameters replaced by `...` to make this more readable.
resource "azurerm_virtual_machine" "database" {
name = "database"
...
}
resource "azurerm_virtual_machine" "webserver" {
name = "webserver"
...
depends_on = [azurerm_virtual_machine.database]
}
In the example above, two virtual machines are created. We as developers may know that the database
needs to be created first, before the webserver
is created.
From a Terraforms perspective, these are just two machines with no specific relation. By adding the depends_on
parameter, Terraform knows it should first create the database
, followed by the webserver
.
A resource can have the depends_on
meta-argument on any resource. The depends_on
, refers to a list of other resources.
resource "azurerm_virtual_machine" "reversed_proxy" {
name = "reversed_proxy"
...
depends_on = [azurerm_virtual_machine.webserver, azurerm_virtual_machine.syslogserver]
}
azurerm_virtual_machine
. (Be aware; a lot of values need to be made unique…)google_compute_instance
.main.tf
matter?resource_group_name = azurerm_resource_group.rg.name
?