Terraform Resources
The most important building block in Terraform is the
resource. A resource represents a piece of infrastructure – a virtual machine, a storage bucket, a DNS record, etc. You declare resources in your configuration, and Terraform creates and manages them.Resource Syntax
A resource block has two string labels: the resource type and the local name. The type determines what provider and kind of resource (e.g.,
aws_instance). The local name is used to refer to the resource elsewhere in the config.resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}Resource Arguments
Inside the block, you provide arguments specific to that resource type. Arguments can be required or optional. For an AWS EC2 instance, common arguments include
ami, instance_type, tags, vpc_security_group_ids, etc.Referencing Resources
Once you create a resource, you can access its attributes using the syntax
<resource_type>.<local_name>.<attribute>. For example, to get the public IP of an EC2 instance:output "ip" {
value = aws_instance.web.public_ip
}Example: Create an AWS Security Group
resource "aws_security_group" "web_sg" {
name = "web-sg"
description = "Allow HTTP and SSH"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}Resource Dependencies
Terraform automatically builds a dependency graph from references. If one resource refers to another, Terraform creates the referenced resource first. You can also force ordering with
depends_on (rarely needed).Two Minute Drill
- Resources are the primary building blocks – they represent infrastructure components.
- Syntax:
resource "type" "name" { ... }. - Access attributes with
type.name.attribute. - Terraform builds a dependency graph automatically.
Need more clarification?
Drop us an email at career@quipoinfotech.com
