Introduction
Terraform’s depends_on meta-argument can be used to create explicit dependencies between resources. This can be useful for ensuring that resources are created in the correct order, or for preventing resources from being deleted if they are still needed by other resources.
Syntax
The depends_on meta-argument takes a list of resource names as its argument. When Terraform creates a resource, it will first check to see if any of the resources in the depends_on list have already been created. If they have, then Terraform will create the resource without waiting for them to be created. If they have not been created, then Terraform will wait for them to be created before creating the resource.
Examples
Here are some examples of using depends_on in Terraform:
- To create an Azure virtual machine only after a network interface has been created:
resource "azurerm_network_interface" "nic" {
name = "my-nic"
}
resource "azurerm_virtual_machine" "vm" {
depends_on = ["azurerm_network_interface.nic"]
name = "my-vm"
}
In this code, the azurerm_virtual_machine.vm
resource depends on the azurerm_network_interface.nic
resource. This means that Terraform will not create the azurerm_virtual_machine.vm
resource until the azurerm_network_interface.nic
resource has been created.
In addition to explicit dependencies, Terraform also supports implicit dependencies. Implicit dependencies are created when a resource references another resource. For example, the following code will create an Azure virtual machine that uses a public IP address:
resource "azurerm_public_ip" "ip" {
name = "my-ip"
}
resource "azurerm_virtual_machine" "vm" {
name = "my-vm"
public_ip_address_id = azurerm_public_ip.ip.id
}
In this code, the azurerm_virtual_machine.vm
resource implicitly depends on the azurerm_public_ip.ip
resource. This is because the azurerm_virtual_machine.vm
resource uses the azurerm_public_ip.ip
resource’s ID as its public_ip_address_id
attribute.
Implicit dependencies can be useful for creating dependencies between resources that are not explicitly defined. However, they can also lead to unexpected behavior. For example, if the azurerm_public_ip.ip
resource is deleted, then the azurerm_virtual_machine.vm
resource will also be deleted, even if it is still needed.
To avoid this problem, it is best to use explicit dependencies whenever possible. Explicit dependencies can be easily managed and controlled, and they can help to prevent unexpected behavior.
Conclusion
Terraform’s depends_on meta-argument can be used to create explicit dependencies between resources. This can be useful for ensuring that resources are created in the correct order, or for preventing resources from being deleted if they are still needed by other resources. However, it is important to use explicit dependencies whenever possible to avoid unexpected behavior.
I hope this blog post has helped you understand how to use depends_on in Terraform.