Convert Terraform Data Sources to JSON
Convert Terraform data source blocks that query existing infrastructure from HCL to JSON. Covers AMI lookups, availability zones, and IAM policies.
Detailed Explanation
Terraform Data Sources
Data sources allow Terraform to read information from existing infrastructure or external services. They use the data block type and are read-only.
HCL Data Source Examples
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"]
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
}
data "aws_availability_zones" "available" {
state = "available"
}
data "aws_iam_policy_document" "assume_role" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ec2.amazonaws.com"]
}
}
}
JSON Structure
Data sources follow the same nesting pattern as resources: data > data source type > data source name > attributes.
{
"data": {
"aws_ami": {
"ubuntu": {
"most_recent": true,
"owners": ["099720109477"],
"filter": {
"name": "name",
"values": ["ubuntu/images/..."]
}
}
}
}
}
Multiple Filter Blocks
When multiple filter blocks appear, they should be collected into a JSON array. Each filter block becomes an object in the array.
IAM Policy Documents
The aws_iam_policy_document data source is one of the most complex, with nested statement, principals, condition, and not_actions blocks. The JSON representation mirrors this nesting faithfully.
Data Source References
Data source values are referenced as data.aws_ami.ubuntu.id in HCL. These expressions become strings in JSON output.
Use Case
Looking up the latest AMI for EC2 instances, querying available AZs for dynamic infrastructure, generating IAM policies programmatically, or building Terraform configurations that reference existing infrastructure.