Terraform implicit dependencies

When you include a reference from one resource to another in Terraform you create an implicit dependency.

The example below shows a basic resource deployment of an AWS instance and security group. Because the aws_instance.example references aws_security_group.instance.id in its vpc_security_group_ids, Terraform automatically knows to create the security group first, then the instance.

provider "aws" {
  region = "eu-west-1"
}

resource "aws_instance" "example" {
  ami           = "ami-080ecf65f4d838a6e"
  instance_type = "t3.micro"
  vpc_security_group_ids = [aws_security_group.instance.id]

  user_data = <<-EOF
             #!/bin/bash

             cd /tmp
             echo "Hello, World" > index.html
             nohup python3 -m http.server 8080 > /tmp/server.log 2>&1 &
             echo "Server started" > /tmp/startup-complete.txt
             EOF

  user_data_replace_on_change = true

  tags = {
    Name = "terraform-example"
    Environment = "development"
    Project = "test"
    Managedby = "terraform"
  }
}
resource "aws_security_group" "instance" {
  name = "terraform-example-instance"
  ingress {
    from_port = 8080
    to_port = 8080
    protocol = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  egress {
    from_port = 8080
    to_port = 8080
    protocol = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }  
 }

Dependencies can be viewed using the terraform graph command.

$ terraform graph