Understand how to read and fetch data from providers without creating or managing resources. Datasources are the bridge between Terraform configurations and existing data in the cloud.

What Will You Learn? #

Datasources let you query information from providers — like finding the latest AMI ID, fetching an existing VPC’s data, or getting availability zone information. Unlike resources that manage lifecycles, datasources only read data.

Articles in This Section #

ArticleMain Topic
What is a Datasource?The concept of datasources and their difference from resources
ReferenceHow to use datasources to reference existing resources
Anti-PatternCommon datasource usage mistakes to avoid

Datasource vs Resource #

flowchart LR
    subgraph Resource["Resource (Manage)"]
        R_Create["terraform apply<br/>Creates/Updates"]
        R_State["Tracks in<br/>State File"]
        R_Life["Full Lifecycle<br/>CRUD"]
    end

    subgraph Datasource["Datasource (Read)"]
        D_Read["terraform plan<br/>Reads Only"]
        D_NoState["No State<br/>Changes"]
        D_Query["Query/API<br/>Call"]
    end

    R_Create --> R_State --> R_Life
    D_Read --> D_NoState --> D_Query

    style Resource fill:#ffebee
    style Datasource fill:#e8f5e9

Common Datasource Patterns #

flowchart TD
    subgraph Lookup["Data Lookup"]
        AMI["data.aws_ami<br/>Find the latest AMI"]
        VPC["data.aws_vpc<br/>Get an existing VPC"]
        AZ["data.aws_availability_zones<br/>List zones"]
    end

    subgraph Use["Used In Resources"]
        EC2["aws_instance<br/>ami = data.aws_ami.id"]
        SUBNET["aws_subnet<br/>vpc_id = data.aws_vpc.id"]
        RDS["aws_db_instance<br/>availability_zone"]
    end

    AMI --> EC2
    VPC --> SUBNET
    AZ --> RDS

    style Lookup fill:#e3f2fd
    style Use fill:#e8f5e9

Datasource Anti-Pattern #

# ❌ Anti-Pattern: Hardcode the AMI ID
ami = "ami-0abcdef1234567890"

# ✅ Best Practice: Use a datasource
data "aws_ami" "latest" {
  most_recent = true
  owners      = ["amazon"]
  filter {
    name   = "name"
    values = ["amzn2-ami-hvm-*-x86_64-gp2"]
  }
}
ami = data.aws_ami.latest.id

After understanding datasources, continue to Module & Reusability to learn how to create reusable code.

About | Author | Content Scope | Editorial Policy | Privacy Policy | Disclaimer | Contact