Convert AWS EC2 Instance HCL to JSON
Convert a Terraform AWS EC2 instance resource with tags, block devices, and user data from HCL to JSON format.
Detailed Explanation
AWS EC2 Instance Configuration
The aws_instance resource is one of the most common Terraform resources. Its HCL-to-JSON conversion demonstrates how resource blocks, nested blocks, maps, and string values translate.
Complete EC2 HCL Example
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
key_name = "my-key-pair"
vpc_security_group_ids = ["sg-abc123"]
subnet_id = "subnet-xyz789"
tags = {
Name = "web-server"
Environment = "production"
}
root_block_device {
volume_size = 20
volume_type = "gp3"
encrypted = true
}
metadata_options {
http_endpoint = "enabled"
http_tokens = "required"
}
}
JSON Equivalent
In Terraform's JSON syntax, the three-level nesting (resource > resource type > resource name) wraps the configuration body. Lists like vpc_security_group_ids remain as JSON arrays. Nested blocks like root_block_device and metadata_options become nested JSON objects.
Important Considerations
- Tags map: The
tagsattribute is a map, not a block, so it uses=assignment in HCL and becomes a regular JSON object. - Security group IDs: List values maintain their array structure in JSON.
- Nested blocks:
root_block_deviceandmetadata_optionsare blocks (no=sign), becoming nested objects. - IMDSv2: The
metadata_optionsblock withhttp_tokens = "required"enforces IMDSv2, a security best practice.
Use Case
Converting EC2 instance definitions to JSON for programmatic infrastructure provisioning, generating Terraform configurations from deployment scripts, or migrating infrastructure definitions between HCL and JSON formats in CI/CD pipelines.