Skip to content

Data Sources & Resources

Terraform data sources and resource types are foundational to managing infrastructure as code. Data sources allow you to read existing infrastructure (e.g., AWS VPCs, DNS records) without modifying them, while resource types define how to provision new infrastructure (e.g., EC2 instances, S3 buckets). Together, they enable declarative workflows for both existing and new resources.


Data Sources: Querying Existing Infrastructure

Data sources are used to retrieve information about resources already managed by other tools or manually configured in the cloud. They are read-only and cannot create or modify resources.

Syntax

data "provider_type" "name" {
  # Configuration arguments
}

Example: Querying an Existing AWS VPC

data "aws_vpc" "main_vpc" {
  tags = {
    Environment = "production"
  }
}

This data source retrieves the ID of a VPC tagged with Environment=production. You can reference its attributes like data.aws_vpc.main_vpc.id in other resources.

Use Cases

  • Discovering existing resources (e.g., finding an existing subnet ID).
  • Using existing infrastructure as input for new resources (e.g., creating a route table based on an existing VPC).

Resource Types: Provisioning New Infrastructure

Resource types define how Terraform provisions new infrastructure using providers. Each resource has a type (e.g., aws_instance for EC2) and a name. Providers handle the underlying API interactions.

Syntax

resource "provider_type" "name" {
  # Configuration arguments
}

Example: Creating an AWS EC2 Instance

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  tags = {
    Name = "example-instance"
  }
}

This resource creates an EC2 instance using the specified AMI and tags. Terraform manages the lifecycle, ensuring the instance matches the declared state.

Provider Configuration

Providers must be configured with credentials and region settings. Example:

provider "aws" {
  region  = "us-west-2"
  access_key = "YOUR_ACCESS_KEY"
  secret_key = "YOUR_SECRET_KEY"
}


Key Takeaways

  • Data sources read existing infrastructure (e.g., aws_vpc) and are used to reference attributes in other resources.
  • Resource types define how to provision new infrastructure (e.g., aws_instance) and require provider configuration.
  • Always use data for existing resources and resource for new ones to avoid unintended modifications.
  • Providers must be explicitly configured with credentials and region settings for resource provisioning.