DEV Community

Felipe Arcaro
Felipe Arcaro

Posted on

Creating an AWS EC2 instance with Terraform

TL;DR

Here's the Terraform code to create an EC2 instance:

resource "aws_instance" "my_project_ec2" {
  instance_type = "t2.micro"
  ami = "ami-06e46074ae430fba6"
  tags = {
    Name = "my-python-project"
  }
}

Enter fullscreen mode Exit fullscreen mode

EC2 Instance (Elastic Compute Cloud)

Elastic Compute Cloud (EC2) is a virtual server provided by AWS that allows you to run applications and services in the cloud - it's just a regular computer but in the cloud.

EC2 is awesome because:

  • We don't need to invest in infrastructure upfront
  • It allows us to scale up/down (vertically) to handle different workloads
  • It offers different purchasing options (on demand, reserved, spot)

Terraform it up

We're past the basics now, so let's create an EC2 instance. Here's the code to do it:

resource "aws_instance" "my_project_ec2" {
  instance_type = "t2.micro"
  ami = "ami-06e46074ae430fba6"
  tags = {
    Name = "my-python-project"
  }
}
Enter fullscreen mode Exit fullscreen mode

The resource name my-python-project that comes after the resource type aws_instance is not the same as the resource name that appears in the Admin Console. For that, I had to use tags parameter.

Once again, the infrastructure is updated after we run terraform plan and terraform apply and a new EC2 instance is created.i

Wait, what is AMI?

Amazon Machine Image (AMI) is a pre-configured package required to launch an EC2 instance that includes an operating system, software packages and other requirements. It's essentially a template that can be used to launch EC2 instances (Linux, Windows or Mac)

AMI is awesome because:

  • We don't need to manually install packages and requirements
  • We can launch several EC2 with the same configuration (load balancing)
  • When selecting the AMI, we can use the Advanced Details tab to run a bash script (e.g. to update yum and install httpd)

Ok. So far, we have a computer where we can run our project and a database in which we can persist and read data. Now it's time to give them proper access - in other words, we have to specify what AWS resources and who should be able to access them.

Top comments (0)