IaC: Dependency Management
How resource dependencies work, topological ordering, and parallel deployment.
IaC: Dependency Management
Overview
The dependsOn field in resource declarations defines the order in which resources are created, updated, and deleted. The IaC engine uses topological sorting to determine the correct execution order.
Declaring Dependencies
Use the dependsOn array to list resources that must exist before the current resource is created:
{
"apiVersion": "v1",
"kind": "Instance",
"metadata": {"name": "web-server"},
"spec": {
"type": "cx31",
"image": "ubuntu-22.04",
"vpc_id": "production-vpc",
"subnet_id": "web-subnet"
},
"dependsOn": ["web-subnet", "web-sg"]
}
The dependsOn values are the metadata.name of other resources in the same stack.
Topological Ordering
The engine builds a directed acyclic graph (DAG) from all dependsOn declarations and performs a topological sort to determine execution order.
Example Dependency Graph
VPC
├── Subnet
│ └── Instance
│ └── DNSRecord
├── SecurityGroup
│ └── Instance (also depends on Subnet)
└── LoadBalancer
└── DNSRecord (also depends on Instance)
Resulting Execution Order
- Level 0 (no dependencies): VPC
- Level 1 (depends on VPC): Subnet, SecurityGroup, LoadBalancer
- Level 2 (depends on Level 1): Instance
- Level 3 (depends on Level 2): DNSRecord
Parallel Deployment
Resources at the same dependency level are deployed in parallel. In the example above:
- Subnet, SecurityGroup, and LoadBalancer start simultaneously after VPC completes
- Instance starts after both Subnet and SecurityGroup complete
- DNSRecord starts after both Instance and LoadBalancer complete
This parallelism significantly reduces total deployment time for complex stacks.
Circular Dependency Detection
The engine detects circular dependencies during validation:
{
"resources": [
{"kind": "Instance", "metadata": {"name": "a"}, "dependsOn": ["b"]},
{"kind": "Instance", "metadata": {"name": "b"}, "dependsOn": ["a"]}
]
}
Validation failed:
error: circular dependency detected: a → b → a
Circular dependencies are rejected at validation time, before any resources are created.
Deletion Order
When destroying a stack, resources are deleted in reverse topological order:
- DNSRecord (leaf nodes first)
- Instance, LoadBalancer
- Subnet, SecurityGroup
- VPC (root node last)
This ensures dependent resources are removed before their dependencies, preventing orphaned references and API errors.
Implicit Dependencies
Some dependencies are implicit based on spec references. If a resource's spec contains a vpc_id referencing another resource's name, the engine infers a dependency even without an explicit dependsOn. However, explicit declarations are recommended for clarity.