Day 03 Applied Skills

Resources and Data Sources

Define EC2 instances, security groups, and VPCs. Use data sources to reference existing infrastructure.

~1 hour Hands-on Precision AI Academy

Today's Objective

Learn the core concepts of Resources and Data Sources and apply them in practical exercises.

01

Real Resources: VPC + EC2

vpc.tf
vpc.tf
# Create a VPC
resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
  tags = { Name = "main-vpc" }
}

# Public subnet
resource "aws_subnet" "public" {
  vpc_id            = aws_vpc.main.id  # reference another resource
  cidr_block        = "10.0.1.0/24"
  availability_zone = "us-east-1a"
  map_public_ip_on_launch = true
}

# Security group
resource "aws_security_group" "web" {
  vpc_id = aws_vpc.main.id

  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"]
  }
}
ec2.tf
ec2.tf
data "aws_ami" "amazon_linux" {
  most_recent = true
  owners      = ["amazon"]
  filter {
    name   = "name"
    values = ["al2023-ami-*-x86_64"]
  }
}

resource "aws_instance" "web" {
  ami                    = data.aws_ami.amazon_linux.id
  instance_type          = "t3.micro"
  subnet_id              = aws_subnet.public.id
  vpc_security_group_ids = [aws_security_group.web.id]

  user_data = <<-EOF
    #!/bin/bash
    yum install -y nginx
    systemctl start nginx
    EOF

  tags = { Name = "web-server" }
}
â„šī¸
References like aws_vpc.main.id create implicit dependencies. Terraform builds a dependency graph and creates resources in the right order. The subnet waits for the VPC. The EC2 waits for the subnet. You don't have to specify the order.

Supporting References & Reading

Go deeper with these external resources.

Terraform Docs
Resources and Data Sources Official HashiCorp Terraform documentation.
→
YouTube
Resources and Data Sources Terraform tutorials on YouTube
→
MDN
MDN Web Docs Comprehensive web technology reference
→

Day 3 Checkpoint

Before moving on, confirm understanding of these key concepts:

Continue To Day 4
Day 4 of the Terraform in 5 Days course
→