Skip to content

Resources

Resources are the core building blocks of the infrastructure being managed. A resource represents a single component or object in a provider, such as an EC2 instance in AWS or a virtual machine in Azure.

Resources are declared in HCL using a resource block syntax.

Here’s an example of a resource definition for an AWS EC2 instance:

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

In this example, the aws_instance resource block defines an EC2 instance with the AMI ID of ami-0c55b159cbfafe1f0 and the instance type of t2.micro. The tags block is used to define metadata for the instance.

You can also create resources dependencies between objects, you do this if you reference a property as a value in another resource!

In this example, the aws_instance resource block has a vpc_security_group_ids parameter that references the id of the aws_security_group resource block. This establishes a dependency relationship between the two resources. Terraform can ensure that the security group resource is created before the EC2 instance, so it can be created with the appropriate properties.

resource "aws_security_group" "web" {
name_prefix = "web-"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
vpc_security_group_ids = [aws_security_group.web.id]
}

Resources are the building blocks for defining and managing infrastructure as code. They allow you to create, modify, and delete infrastructure resources in a safe and repeatable way, ensuring that your infrastructure remains consistent and reproducible.