You already have the network ready (VPC, public subnet, Internet Gateway, and routes). Now let's add the main character: an EC2 server inside that subnet, accessible from the internet. Remember everything from Chapter 4 about instances; now we'll write it in Terraform.

What We Will Add

On top of the network from the previous subchapter, we add an EC2 instance:

┌──────────── VPC (10.0.0.0/16) ────────────┐
│   ┌─ Public Subnet (10.0.1.0/24) ─┐       │
│   │   ┌──────────────────┐          │      │
│   │   │   EC2 Instance   │ ◄── new  │      │
│   │   │   (web server)   │          │      │
│   │   └──────────────────┘          │      │
│   └─────────────────────────────────┘      │
└────────────────────────────────────────────┘

Step 1: Find the AMI (the base image)

Remember that every instance starts from an AMI (subchapter 4.2). Instead of manually writing an AMI ID (which changes over time and by region), it's best to automatically find the most recent one with a data block:

data "aws_ami" "amazon_linux" {
  most_recent = true
  owners      = ["amazon"]

  filter {
    name   = "name"
    values = ["al2023-ami-*-x86_64"]
  }
}

What is a data block? It's an important new concept: while resource creates something, a data block (data source) queries existing information in AWS without creating anything. Here we ask AWS "what is the most recent Amazon Linux 2023 AMI?" and save the answer to use it. It's very useful to avoid writing hardcoded values that expire.

Step 2: Define variables (best practice)

To make the code flexible (subchapter 10.1), we define some variables:

variable "tipo_instancia" {
  description = "EC2 instance type"
  type        = string
  default     = "t3.micro"     # eligible for free tier (Chapter 4)
}

variable "nombre_proyecto" {
  type    = string
  default = "mi-primer-servidor"
}

Using t3.micro (subchapter 4.1) is ideal for learning, because it's included in the AWS free tier.

Step 3: Create the EC2 instance

Now the main resource. We place it in our public subnet:

resource "aws_instance" "web" {
  ami                    = data.aws_ami.amazon_linux.id   # the AMI we found
  instance_type          = var.tipo_instancia             # the variable
  subnet_id              = aws_subnet.publica.id          # ← in the public subnet
  vpc_security_group_ids = [aws_security_group.web.id]    # firewall (subchap. 12.3)

  tags = {
    Name = var.nombre_proyecto
  }
}

Let's analyze the connections:

  • ami → reference to the data source from step 1 (the AMI found).
  • instance_type → the variable from step 2.
  • subnet_id → reference to the public subnet from subchapter 12.1. This places the server in our network, in the public zone.
  • vpc_security_group_ids → reference to the Security Group (the firewall), which we will create in the next subchapter.

Each reference creates a dependency: Terraform will create the subnet and Security Group first, and then the instance.

Step 4: Install software at startup (user_data)

Often you want the server to do something as soon as it starts, like installing a web server. For that, there is user_data: a script that runs automatically the first time the instance starts.

resource "aws_instance" "web" {
  ami                    = data.aws_ami.amazon_linux.id
  instance_type          = var.tipo_instancia
  subnet_id              = aws_subnet.publica.id
  vpc_security_group_ids = [aws_security_group.web.id]

  user_data = <<-EOF
    #!/bin/bash
    yum update -y
    yum install -y httpd
    systemctl start httpd
    systemctl enable httpd
    echo "<h1>Hello from my first server on AWS with Terraform!</h1>" > /var/www/html/index.html
  EOF

  tags = {
    Name = var.nombre_proyecto
  }
}

This script: updates the system, installs the Apache web server (httpd), starts it, and creates a welcome page. When the instance is ready, it will serve a website with that message.

What we just achieved: with user_data, the server self-configures at birth. You don't need to connect to install anything manually. This is key for automation and for autoscaling (Chapter 13): each new server prepares itself. (For complex configurations, it's better to create a ready-made AMI, remember subchapter 4.2, but user_data is perfect to start.)

The current state

Right now we have:

✓ Complete network (subchapter 12.1)
✓ An AMI found automatically (data source)
✓ An EC2 instance in the public subnet
✓ A script that installs a web server at startup
✗ Missing: the Security Group (firewall) — subchapter 12.3
✗ Missing: a fixed IP and the outputs — subchapters 12.3 and 12.4

If you ran plan now, Terraform would complain that the Security Group (aws_security_group.web) we referenced is missing and hasn't been created yet. We'll solve that in the next subchapter.

What you should remember

  • A data block (data source) queries existing information in AWS without creating anything (we use it to find the most recent AMI automatically, avoiding hardcoded IDs that expire).
  • The instance is placed in the subnet with subnet_id, referencing the public subnet from the previous chapter.
  • Using variables (like tipo_instancia) makes the code flexible; t3.micro is ideal for the free tier.
  • user_data is a script that the server runs at startup, perfect for self-configuration (installing software, etc.) without manual intervention.
  • References between resources create dependencies and the automatic creation order.

In the next subchapter, we will create the missing Security Group (firewall) and assign the server a fixed Elastic IP.

Cloud, AWS & Terraform — From Zero to Expert

Chapter 1 · What is cloud computing

Chapter 2 · The cloud market and major providers

Chapter 3 · Regions, availability zones and edge

Chapter 4 · Compute: EC2

Chapter 5 · Storage: S3

Chapter 6 · Networking: VPC

Chapter 7 · Identity and access: IAM

Chapter 8 · Managed databases

Chapter 9 · Why Infrastructure as Code

Chapter 10 · HCL: the Terraform language

Chapter 11 · Providers and state

Chapter 12 · Your first real infrastructure in Terraform

Chapter 13 · Load balancing and auto scaling

Chapter 14 · Serverless with Lambda

Chapter 15 · Messaging and events

Chapter 16 · Content delivery and DNS

Chapter 17 · Containers on AWS

Chapter 18 · Modules: reuse and composition

Chapter 19 · Workspaces and environment management

Chapter 20 · Remote backends and locking

Chapter 21 · Infrastructure testing

Chapter 22 · Terraform in CI/CD

Chapter 23 · Defense in depth

Chapter 24 · Observability: logs, metrics and traces

Chapter 25 · Cost optimization

Chapter 26 · High availability and disaster recovery

Chapter 27 · AWS Well-Architected Framework

Chapter 28 · Serverless architectures at scale

Chapter 29 · Data platforms on AWS

Chapter 30 · Multi-account and landing zones

Chapter 31 · Platform Engineering and Internal Developer Platform

Chapter 32 · Relevant AWS certifications

Chapter 33 · Projects to consolidate what you've learned

Chapter 34 · Resources and community

© Copyright 2024. All rights reserved