Working with Terraform Resources:
Building and Managing Infrastructure as Code.
At the heart of Terraform lies the concept of resources. A resource is a piece of infrastructure or service that you want to manage using Terraform. It could be a virtual machine, a cloud database, a network security group, or any other infrastructure component. Terraform resources are defined using Hashicorp Configuration Language (HCL) within a Terraform configuration file (usually with a .tf
extension).
Resource Attributes
Resources also have attributes, which are the properties or settings for that resource. In the above EC2 instance resource, ami
and instance_type
are attributes. You set these attributes to configure the resource to your specifications.
Resource Dependencies
Resources can depend on each other. For instance, if your EC2 instance needs to be associated with a security group, you declare that dependency in Terraform:
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
resource "aws_security_group" "example" {
name = "example"
description = "Allow inbound traffic on port 80"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_network_interface_sg_attachment" "example" {
security_group_id = aws_security_group.example.id
network_interface_id = aws_instance.example.network_interface_ids[0]
}
Here, we have an EC2 instance that depends on a security group, and a network interface that connects them.
Resource Lifecycle
Terraform manages the lifecycle of resources. When you apply your configuration, Terraform creates or updates the resources as needed. You can also destroy resources using Terraform, which is crucial for cost control and decommissioning infrastructure.
Applying Changes
To apply your Terraform configuration and create or update resources, you use the terraform apply
command. Terraform calculates and displays the changes it will make before you confirm the action.
Conclusion
Terraform resources are the building blocks of your infrastructure. They allow you to define, configure, and manage the components that make up your environment in a consistent and repeatable manner. By declaring resources and their attributes, you're defining your infrastructure as code, which means you can version, share, and automate the provisioning and management of your infrastructure.