Ravindra BagaleCourses & study guides Track your progress

Labs · DevOps

Lab: Launch an EC2 Instance with Terraform (AMI Data Source, Security Group, IMDSv2, Encrypted Disk) and Serve an nginx Page from user_data

Beginner30 minTerraform 1.6+ · AWS CLI v2 · An AWS account

Course: DevOps · Chapter 44: Terraform AWS Guides EC2 RDS S3 Security Groups IAM ALB and Auto Scaling · Lesson: 44.1 How to launch an EC2 instance with Terraform

Lesson 44.1 explains every line of these files; this lab walks through running them and cleaning up.

Chala mitrano! Console madhe dahaa screen click karnyapeksha chaar files. Aaj Terraform ne EC2 launch karuya, ani lagech destroy.

Suppose we are…

Suppose we are on a Netflix-style platform team and a developer needs one test web server for a demo today. Clicking through the console takes ten screens and nobody remembers which options were picked. With Terraform the same server comes from four small files, the review happens in a pull request, and terraform destroy removes it when the demo is over. This guide uses the default VPC so you can focus only on EC2.

Goal of this lab

By the end you will have:

  • A running EC2 instance from code, with no SSH port open.
  • The page Hello from Terraform EC2 returned by curl.
  • Everything destroyed with one command.

What you need

  • Terraform 1.6 or newer (terraform version).
  • AWS CLI v2 signed in to your own AWS account with an IAM user or SSO role that may create these resources (aws sts get-caller-identity works). Never use the root user, and never paste access keys into .tf files.
  • Region Mumbai (ap-south-1) is used; change region if you prefer another.
  • 30 minutes.

Cost and cleanup

A t3.micro instance is free-tier eligible in many accounts but can be billed. Small charges are possible even on the free tier. Finish the lab in one sitting and always run the Clean up part at the end.

Part 1: Create the project files

  1. Create the folder:

    mkdir ec2-guide && cd ec2-guide
    

    What you should see: after the next steps, this layout:

    ec2-guide/
    ├── versions.tf
    ├── variables.tf
    ├── main.tf
    └── outputs.tf
    
  2. Create versions.tf:

    versions.tf

    terraform {
      required_version = ">= 1.6"
      required_providers {
        aws = {
          source  = "hashicorp/aws"
          version = "~> 5.0"
        }
      }
    }
    
    provider "aws" {
      region = var.region
    }
    
  3. Create variables.tf:

    variables.tf

    variable "region" {
      type    = string
      default = "ap-south-1"
    }
    
    variable "instance_type" {
      type    = string
      default = "t3.micro"
    }
    
  4. Create main.tf:

    main.tf

    data "aws_ami" "al2023" {
      most_recent = true
      owners      = ["amazon"]
      filter {
        name   = "name"
        values = ["al2023-ami-2023.*-x86_64"]
      }
    }
    
    data "aws_vpc" "default" {
      default = true
    }
    
    data "aws_subnets" "default" {
      filter {
        name   = "vpc-id"
        values = [data.aws_vpc.default.id]
      }
    }
    
    resource "aws_security_group" "web" {
      name        = "guide-ec2-web"
      description = "HTTP in, all out"
      vpc_id      = data.aws_vpc.default.id
    }
    
    resource "aws_vpc_security_group_ingress_rule" "http" {
      security_group_id = aws_security_group.web.id
      cidr_ipv4         = "0.0.0.0/0"
      ip_protocol       = "tcp"
      from_port         = 80
      to_port           = 80
    }
    
    resource "aws_vpc_security_group_egress_rule" "all" {
      security_group_id = aws_security_group.web.id
      cidr_ipv4         = "0.0.0.0/0"
      ip_protocol       = "-1"
    }
    
    resource "aws_instance" "web" {
      ami                         = data.aws_ami.al2023.id
      instance_type               = var.instance_type
      subnet_id                   = data.aws_subnets.default.ids[0]
      vpc_security_group_ids      = [aws_security_group.web.id]
      associate_public_ip_address = true
    
      metadata_options {
        http_tokens = "required"
      }
    
      root_block_device {
        volume_size = 8
        volume_type = "gp3"
        encrypted   = true
      }
    
      user_data = <<-EOT
        #!/bin/bash
        dnf install -y nginx
        echo "Hello from Terraform EC2" > /usr/share/nginx/html/index.html
        systemctl enable --now nginx
      EOT
    
      tags = {
        Name = "guide-ec2-web"
      }
    }
    
  5. Create outputs.tf:

    outputs.tf

    output "public_ip" {
      value = aws_instance.web.public_ip
    }
    
    output "web_url" {
      value = "http://${aws_instance.web.public_dns}"
    }
    

Part 2: Init, check and plan

  1. Download the AWS provider:

    terraform init
    

    What you should see: Terraform has been successfully initialized!

  2. Format and validate:

    terraform fmt
    terraform validate
    

    What you should see: Success! The configuration is valid.

  3. Plan and read the counts:

    terraform plan
    

    What you should see: $ terraform apply

Part 3: Apply and test

  1. Apply and type yes:

    terraform apply
    
  2. Wait about two minutes for user_data to install nginx, then curl the output URL:

    curl -s $(terraform output -raw web_url)
    

    What you should see: the apply summary and the page:

    $ terraform apply
    Plan: 4 to add, 0 to change, 0 to destroy.
    aws_instance.web: Creation complete after 13s [id=i-0a1b2c3d4e5f...]
    Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
    Outputs:
    web_url = "http://ec2-13-xxx-xxx-xxx.ap-south-1.compute.amazonaws.com"
    
    $ curl -s $(terraform output -raw web_url)
    Hello from Terraform EC2
    

Clean up: destroy everything

  1. Delete everything this lab created. Type yes when asked:

    terraform destroy
    

    What you should see: Plan: 0 to add, 0 to change, 4 to destroy. then Destroy complete! Resources: 4 destroyed.

Ravindra Bagale's Tip

There is no port 22 rule in this lab on purpose. For shell access use Session Manager with an IAM role (see the VPC lab), not an SSH key and an open port.

Common mistakes

MistakeWhat happensFix
Error: creating EC2 Instance: InvalidParameterCombination:Apply stopsFor the instance type, pick one offered in your region (t3.micro or t2.micro). For the AMI, check the name filter and the region; run aws ec2 describe-images --owners amazon --filters Name=name,Values=al2023-ami-2023.*-x86_64 to see what matches. If curl times out, wait two minutes for user_data to finish, then check the port 80 rule.
curl times out right after applynginx is still installingWait two minutes for user_data to finish
Skipping terraform planSurprise changes or deletesAlways read the plan counts before apply
Access keys written in .tf filesKeys end up in Git and in stateUse aws configure sso or a profile; roles in CI

Self-check checklist

0 of 4 done

Try-at-home challenge

Add a variable instance_count and use count to launch two instances, each printing its own index in the page. Output both public IPs as a list.

Samajla ka? Four files, one server, one destroy. Aata pudhe jaauya RDS.