Compute: An EC2 Instance
An EC2 instance is a virtual server in AWS. It boots from an image, runs in a subnet, and is guarded by a security group.
An image and a size
The AMI is a placeholder the emulator accepts: ami-12345678.
resource "aws_instance" "web" {
ami = "ami-12345678"
instance_type = "t3.micro"
}Place it in the network
The subnet and the security group come from lesson 39. The instance joins the VPC through them.
resource "aws_instance" "web" {
ami = "ami-12345678"
instance_type = "t3.micro"
subnet_id = aws_subnet.public.id
vpc_security_group_ids = [aws_security_group.web.id]
}Run it on the emulator
Placeholder credentials point the provider at moto_server. Destroy at the end removes the instance and the network.
export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=test
terraform init
terraform apply
terraform destroyExample
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "6.72.0"
}
}
}
provider "aws" {
region = "us-east-1"
skip_credentials_validation = true
skip_metadata_api_check = true
skip_requesting_account_id = true
endpoints {
ec2 = "http://localhost:5000"
}
}
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
}
resource "aws_subnet" "public" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.1.0/24"
}
resource "aws_security_group" "web" {
name = "lesson-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"]
}
}
resource "aws_instance" "web" {
ami = "ami-12345678"
instance_type = "t3.micro"
subnet_id = aws_subnet.public.id
vpc_security_group_ids = [aws_security_group.web.id]
tags = {
Name = "lesson-web"
}
}
output "instance_id" {
value = aws_instance.web.id
}Key points
- An instance is a virtual server that runs in the cloud.
- The AMI is the image the instance boots from.
- The instance type sets its size, such as t3.micro.
- The subnet decides which network the instance joins.
- A security group decides which traffic can reach the instance.
- The instance id is the value other resources use to refer to it.
The configuration rebuilds the small VPC from lesson 39, then places one instance inside its public subnet with the web security group. The AMI id ami-12345678 is a placeholder the emulator accepts. Nothing here touches real AWS: the instance lives in the mock cloud on this machine. Destroy when done, and the instance and network are gone.
Note
The instance is created in moto_server on this machine. No real AWS account is involved.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What decides where an instance sits and which traffic can reach it?