Asterix
Asterix

Reputation: 433

Order of resource creation in Terraform template

I have created terraform template (azure) with two modules. One module is for the resource group. the other is for vnet (it handles the creation of NSG and route table as well along with their association with subnets).

When I run terraform apply, it is giving an error for the route table, as the resource group is not created yet. the order of creation is showing as route table is created first and then resource group. Is there a way to set the order of creation? in the main.tf in the root folder, module resource group is called first and then vnet.

Upvotes: 3

Views: 10427

Answers (3)

Aditya Garg
Aditya Garg

Reputation: 66

Another alternative would be to use implicit dependence:
-Have the root module where resource group is actually defined return an output:

output "rg_name" {
    value = azurerm_resource_group.root_rg.name
}

-No modifications in resource group module which calls the root module

-While creating route table(module),use the output value from resource group module:

[Assuming the variable assignment in below module is providing input to its root source using the name resource_group_name]

resource_group_name  =module.rg_module["<OPTIONAL KEY IF USING FOR EACH IN RG MODULE"].rg_name

This creates an internal dependence on the resource group.

Note that it is not possible to reference arguments(actually variables) from the resource group module unless output values were defined.

Upvotes: 2

Parthiban Sekar
Parthiban Sekar

Reputation: 49

You must use -out option to save the plan to a file. Like:

terraform plan -out <plan_file>

It is always recommended to use -out and save the plan file. This will ensure that the order of creation is preserved across subsequent applies.

Upvotes: 1

Kamil Wiecek
Kamil Wiecek

Reputation: 213

Reconsider the idea of creating RG and resources using two modules. Ask yourself a simple question: why?

If you are 100% sure it is the right approach then use depends_on:

module "rg1" {
  source = "./rg_module"
  ...
}

module "net1" {
  source = "./network_module"
  ....
  depends_on = [module.rg1]
}

Upvotes: 2

Related Questions