Resource Blocks

Resources are the most important element in Terraform; each one describes one piece of infrastructure.

Syntaxresource "aws_instance" "web" { ami = "ami-..." instance_type = "t3.micro" }

A resource block describes one infrastructure object — a server, a bucket, a DNS record. It is the heart of every Terraform configuration.

Type and name

The two labels are the resource type (aws_instance, defined by the provider) and a local name (web, chosen by you). Together they form the resource's address: aws_instance.web.

Resource addressing

You reference a resource's attributes elsewhere using dot notation, for example aws_instance.web.id or aws_instance.web.public_ip.

Example

Example · hcl
resource "aws_instance" "web" {
  ami           = "ami-0c02fb55956c7d316"
  instance_type = "t3.micro"

  tags = {
    Name = "soundscode-web"
  }
}

# Address of this resource: aws_instance.web
# Its public IP:            aws_instance.web.public_ip

When to use it

  • A developer writes their first resource block to create an S3 bucket and immediately gains reproducible, version-controlled bucket creation.
  • A team audit finds every cloud resource their app needs is declared in .tf files, giving them a full inventory without logging into the console.
  • An SRE replaces a bash provisioning script with resource blocks, eliminating manual steps and making the environment rebuildable from code.

More examples

Simple S3 bucket resource

Declares a minimal aws_s3_bucket resource with a name and tags — the most common starting resource block.

Example · hcl
resource "aws_s3_bucket" "app_data" {
  bucket = "my-app-data-2024"

  tags = {
    Name        = "App Data"
    Environment = "production"
  }
}

EC2 instance resource block

Shows a more complete EC2 resource that references other resources by attribute, linking VPC, subnet, and security group.

Example · hcl
resource "aws_instance" "web" {
  ami                    = "ami-0c55b159cbfafe1f0"
  instance_type          = "t3.small"
  subnet_id              = aws_subnet.public.id
  vpc_security_group_ids = [aws_security_group.web.id]

  tags = {
    Name = "web-server"
  }
}

Reference a resource's output attribute

Attaches an Elastic IP to the web instance using its .id attribute, and exposes the resulting public IP as an output.

Example · hcl
resource "aws_eip" "web" {
  instance = aws_instance.web.id
  domain   = "vpc"
}

output "web_public_ip" {
  value = aws_eip.web.public_ip
}

Discussion

  • Be the first to comment on this lesson.