AWS EC2 Deployment
In this chapter, we'll deploy a real AWS EC2 instance using Terraform. You'll learn how to configure the AWS provider, create a key pair, and launch an instance with user data.
Prerequisites
- AWS account with programmatic access keys.
- AWS CLI configured (
aws configure) or environment variablesAWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEY. - Terraform installed.
Step 1: Configure AWS Provider
Create
main.tf:terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}Step 2: Create a Key Pair (Optional)
To SSH into the instance, create an AWS key pair:
resource "aws_key_pair" "deployer" {
key_name = "deployer-key"
public_key = file("~/.ssh/id_rsa.pub")
}If you don't have an SSH key, generate one with ssh-keygen -t rsa.Step 3: Launch an EC2 Instance
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"]
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
}
}
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"
key_name = aws_key_pair.deployer.key_name
tags = {
Name = "terraform-web"
}
user_data = <<-EOF
#!/bin/bash
apt-get update
apt-get install -y nginx
systemctl start nginx
EOF
}
output "public_ip" {
value = aws_instance.web.public_ip
}Step 4: Deploy
terraform init
terraform plan
terraform applyAfter apply, you'll see the public IP. Open http://<public-ip> in your browser to see Nginx.Two Minute Drill
- Configure AWS provider with region and credentials.
- Use data source
aws_amito fetch latest Ubuntu AMI. - Launch EC2 instance with key pair and user data script.
- Output the public IP to access the web server.
Need more clarification?
Drop us an email at career@quipoinfotech.com
