Format Data Source Blocks

Format Terraform data source blocks for looking up existing infrastructure including AMIs, availability zones, IAM policies, and remote state references.

Advanced Patterns

Detailed Explanation

Formatting Data Source Blocks

Data sources let you reference existing infrastructure that Terraform does not manage. They follow the same formatting rules as resources but use the data keyword.

Common Data Source Examples

data "aws_availability_zones" "available" {
  state = "available"

  filter {
    name   = "opt-in-status"
    values = ["opt-in-not-required"]
  }
}

data "aws_ami" "ubuntu" {
  most_recent = true
  owners      = ["099720109477"] # Canonical

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }
}

data "aws_caller_identity" "current" {}

data "aws_region" "current" {}

Remote State Data Source

data "terraform_remote_state" "network" {
  backend = "s3"

  config = {
    bucket = "my-terraform-state"
    key    = "network/terraform.tfstate"
    region = "us-east-1"
  }
}

data "terraform_remote_state" "dns" {
  backend = "s3"

  config = {
    bucket = "my-terraform-state"
    key    = "dns/terraform.tfstate"
    region = "us-east-1"
  }
}

Formatting Details

  • Empty data sources: data "aws_caller_identity" "current" {} stays on one line
  • Filter blocks: Each filter block has its name and values attributes aligned
  • Multiple filters: Separated by blank lines for clarity
  • Comments: Inline comments like # Canonical are preserved and aligned
  • Config blocks: Nested config blocks in remote state follow the same alignment rules

Use Case

Querying existing AWS resources, looking up the latest AMI for EC2 instances, referencing remote state outputs from other Terraform configurations.

Try It — Terraform HCL Formatter

Open full tool