Launching an AWS EC2 Instance Using Terraform

By Łukasz Kallas
Picture of the author
Published on
terraform image

Today we will go through the process of launching an AWS EC2 instance using Terraform. We'll place it in a specific VPC and subnet, allocate a public IP, and install Nginx via a user data script.

Prerequisites

  • Terraform installed on your local machine.
  • AWS account and IAM credentials configured.
  • Existing VPC and subnet created via Terraform.
resource "aws_security_group" "allow_http" {
  name        = "allow_http"
  description = "Allow HTTP traffic"
  vpc_id      = aws_vpc.main_vpc.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" "nginx" {
  ami                    = "ami-0427090fd1714168b"
  instance_type          = "t3.micro"
  subnet_id              = aws_subnet.public_subnet.id
  associate_public_ip_address = true

  security_groups = [aws_security_group.allow_http.id]

  user_data = <<-EOF
              #!/bin/bash
              yum update -y
              yum install -y nginx
              systemctl start nginx
              systemctl enable nginx
              echo "<html>
              <head>
              <title>briefly.dev</title>
              </head>
              <body>
              <h1>briefly.dev</h1>
              </body>
              </html>" > /usr/share/nginx/html/index.html
              EOF

  tags = {
    Name = "nginx-server"
  }
}

output "instance_public_ip" {
  description = "The public IP of the instance"
  value       = aws_instance.nginx.public_ip
}

Stay Tuned

Want to learn?
The best articles, links and news related to software development delivered once a week to your inbox.