search by tags

for the user

adventures into the land of the command line

terraform order of execution

how can we make sure that one resource, which is dependant on another, is created only after another one already exists? for example, we want to create an azure managed mysql db. for this we need to create a resource group, the db, and a firewall rule to access the db. the firewall depends on there being a db, and the db depends on there being a resource group. how do we tell terraform to order these tasks in this particular order:

create resource group, create db, create firewall rule.

like this:

> main.tf

resource "azurerm_resource_group" "my_groovy_resource_group" {
  name     = "${var.resource_group_name}"
  location = "${var.location}"
}

resource "azurerm_mysql_server" "my_groovy_db" {
  depends_on          = ["azurerm_resource_group.my_groovy_resource_group"] <---------- depends on the resource group existing
  name                = "${var.db_server_name}"
  location            = "${var.location}"
  resource_group_name = "${var.resource_group_name}"

  sku {
    .
    .
    .
    .
  }

  storage_profile {
    .
    .
    .
  }

  .
  .
}

resource "azurerm_mysql_firewall_rule" "allow_office" {
  depends_on          = ["azurerm_mysql_server.my_groovy_db"] <---------- depends on the server existing
  name                = "allow_office"
  .
  .
}

when we run terraform, it’ll do it in the order specified:

$ terraform apply
.
.
.
module.server.azurerm_resource_group.my_groovy_resource_group: Creating...
.
.
module.server.azurerm_resource_group.my_groovy_resource_group: Creation complete after 1s ...
module.server.azurerm_mysql_server.my_groovy_db: Creating...
.
.
module.server.azurerm_mysql_server.my_groovy_db: Creation complete after 4m5s ...
module.server.azurerm_mysql_firewall_rule.allow_office: Creating...
.
.
module.server.azurerm_mysql_firewall_rule.allow_office: Creation complete after 16s ...

Apply complete! Resources: 3 added, 0 changed, 0 destroyed.

and when you want to destroy it, it’ll go in reverse order:

$ terraform destroy
.
.
.
module.server.azurerm_mysql_firewall_rule.allow_office: Destroying...
.
.
module.server.azurerm_mysql_firewall_rule.allow_office: Destruction complete after 16s
module.server.azurerm_mysql_server.my_groovy_db: Destroying...
.
.
module.server.azurerm_mysql_server.my_groovy_db: Destruction complete after 15s
module.server.azurerm_resource_group.my_groovy_resource_group: Destroying...
.
.
module.server.azurerm_resource_group.my_groovy_resource_group: Destruction complete after 47s

Destroy complete! Resources: 3 destroyed.

terraform i ❤︎ u