0
0
Terraformcloud~5 mins

Data source dependencies in Terraform - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes in Terraform, you need to use information from existing resources before creating new ones. Data source dependencies help you get this information safely and in the right order.
When you want to get details about an existing cloud resource before creating a new resource that depends on it.
When you need to read configuration or state from outside Terraform to use in your setup.
When you want to avoid hardcoding values by fetching them dynamically from your cloud provider.
When you want to ensure Terraform creates resources in the correct order based on existing data.
When you want to share information between different parts of your Terraform code safely.
Config File - main.tf
main.tf
provider "aws" {
  region = "us-east-1"
}

data "aws_ami" "ubuntu" {
  most_recent = true
  owners      = ["099720109477"]
  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
  }
}

resource "aws_instance" "example" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t2.micro"
  tags = {
    Name = "example-instance"
  }
}

The provider block sets the AWS region.

The data "aws_ami" "ubuntu" block fetches the latest Ubuntu AMI ID dynamically.

The resource "aws_instance" "example" block creates an EC2 instance using the AMI ID from the data source, ensuring the instance uses the latest Ubuntu image.

Commands
This command initializes the Terraform working directory, downloads the AWS provider plugin, and prepares Terraform to run.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/aws... - Installing hashicorp/aws v4.0.0... - Installed hashicorp/aws v4.0.0 (signed by HashiCorp) Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes that are required for your infrastructure.
This command shows what Terraform will do. It reads the data source to get the latest AMI ID and plans to create an EC2 instance using that AMI.
Terminal
terraform plan
Expected OutputExpected
Refreshing Terraform state in-memory prior to plan... An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # aws_instance.example will be created + resource "aws_instance" "example" { + ami = "ami-0abcdef1234567890" + arn = (known after apply) + instance_type = "t2.micro" + tags = { + "Name" = "example-instance" } } Plan: 1 to add, 0 to change, 0 to destroy. ───────────────────────────────────────────────────────────────────────────── Note: You didn't specify an "-out" parameter to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.
This command applies the planned changes, creating the EC2 instance using the AMI ID fetched from the data source.
Terminal
terraform apply -auto-approve
Expected OutputExpected
aws_instance.example: Creating... aws_instance.example: Still creating... [10s elapsed] aws_instance.example: Creation complete after 15s [id=i-0123456789abcdef0] Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
-auto-approve - Automatically approves the apply without asking for confirmation.
This command shows the current state of the infrastructure Terraform manages, including the EC2 instance created with the AMI from the data source.
Terminal
terraform show
Expected OutputExpected
aws_instance.example: id = i-0123456789abcdef0 ami = ami-0abcdef1234567890 instance_type = t2.micro tags = { Name = example-instance }
Key Concept

If you remember nothing else from this pattern, remember: data sources let Terraform safely get information from existing resources so it can create new resources in the right order.

Common Mistakes
Using a data source without referencing its attributes in resources.
Terraform will fetch the data but not use it, so your resources won't get the needed information.
Always reference the data source attributes (like data.aws_ami.ubuntu.id) in your resource definitions.
Hardcoding values instead of using data sources.
Hardcoded values can become outdated and cause errors or security issues.
Use data sources to fetch dynamic or current values automatically.
Not running 'terraform init' before 'terraform plan' or 'apply'.
Terraform won't have the necessary provider plugins and will fail.
Always run 'terraform init' first to set up the working directory.
Summary
Use data sources in Terraform to fetch information from existing resources before creating new ones.
Run 'terraform init' to prepare your environment, then 'terraform plan' to see changes, and 'terraform apply' to create resources.
Reference data source attributes in your resource blocks to ensure dependencies are handled correctly.