How to Configure AWS EC2 with terraform — Terraform Basics

Inzamam Ahmad
4 min readAug 27, 2023

--

A digital architect, simplifying tech management. It translates your ideas into code, crafting and adjusting your digital world effortlessly. Think of it as your blueprint for servers, databases, and more. It unifies multi-cloud environments, enabling seamless transitions. Collaboration is elevated with version control, and its expertise is a career asset in the ever-evolving tech landscape. Welcome to streamlined, scalable, and collaborative tech mastery.

Before we start first we need to learn about some basic things in terraform

Terraform State

It’s the memory bank of your digital world. Think of it as a record keeper, storing the current status of your created resources — from servers to networks. It’s what Terraform refers to when planning changes or updates. This behind-the-scenes snapshot ensures accurate modifications, collaborative efficiency, and the ability to scale without chaos. In essence, Terraform State is your reliable map of the evolving tech landscape.

Providers

They’re the connectors to different tech realms. Imagine them as translators between Terraform’s language and cloud services like AWS, Azure, or Google Cloud. Providers help Terraform understand where to create resources, ensuring your digital universe is aligned with your chosen cloud environment. These magic bridges enable seamless interaction, giving you the power to orchestrate your tech infrastructure across diverse platforms.

Remote State

It’s like sharing your digital blueprint. Instead of keeping your resource status locally, remote state stores it centrally, accessible to your entire team. This promotes collaboration and syncs changes across devices. It’s like having a master copy that everyone can work on, ensuring accurate updates and streamlined teamwork. Remote state in Terraform ensures that everyone’s on the same page when building and managing your digital landscape.

Terraform Resource

It’s a digital building block. Think of it as a command to create, modify, or manage a specific component like a server, database, or network. These resources are defined in code and act as the building materials that Terraform uses to construct and maintain your tech infrastructure.

AWS EC2 server with Terraform

To do this we use “aws_instance” type resource

resource "aws_instance" "web_server"{
ami = ami_0edab43b6fa892279"
instance_type = "t2_micro"
}

Let’s call this resource web_server. It expects two arguments AMI , AMI id and region. We also need to define instance type for this.

Configuring an EC2 Instance with Terraform: Step-by-Step Guide

Setting up an AWS EC2 instance with Terraform is a journey that combines simplicity with powerful automation. Follow these steps to create and configure an EC2 instance using Terraform:

Step 1: Installation and Setup
1. Install Terraform on your local machine. You can download it from the official Terraform website.
2. Configure your AWS credentials. Set up your access key and secret key using the AWS Command Line Interface (CLI) or environment variables.

Step 2: Create a Terraform Configuration File
1. Create a new directory for your Terraform project.
2. Inside the directory, create a file named `main.tf`. This will be your main configuration file.

Step 3: Define Provider and Resource
1. In `main.tf`, define the AWS provider by adding the following code:
```
provider “aws” {
region = “us-east-1” # Replace with your desired region
}
```
2. Below the provider definition, define an EC2 instance resource:

```
resource "aws_instance" "my_instance" {
ami = "ami-0123456789abcdef0" # Replace with your desired AMI ID
instance_type = "t2.micro" # Replace with your desired instance type
}
```

Step 4: Initialize and Apply
1. Open your terminal or command prompt and navigate to your project directory.
2. Run `terraform init` to initialize the project. Terraform will download the necessary provider plugins.
3. Run `terraform apply` to apply your configuration. Terraform will show you the changes it’s about to make. Type `yes` when prompted to confirm.

Step 5: Access and Test
1. After Terraform completes the apply process, it will provide you with information about the created resources, including your new EC2 instance’s public IP address.
2. Use an SSH client to connect to your EC2 instance using the provided IP address and the key pair you’ve configured in your AWS account.

Step 6: Cleanup
1. Once you’re done testing, run `terraform destroy` to tear down the resources created by Terraform. Confirm with `yes` when prompted.

Here is the code for it

# main.tf

provider "aws" {
region = "us-east-1" # Change to your desired AWS region
}

resource "aws_instance" "my_instance" {
ami = "ami-0123456789abcdef0" # Replace with your desired AMI ID
instance_type = "t2.micro" # Replace with your desired instance type

key_name = "my-keypair" # Replace with the name of your AWS key pair
vpc_security_group_ids = [aws_security_group.allow_ssh.id]

tags = {
Name = "MyEC2Instance"
}
}

resource "aws_security_group" "allow_ssh" {
name_prefix = "allow-ssh-"

ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"] # For demonstration purposes; restrict as needed
}
}

Congratulations! You’ve successfully configured an AWS EC2 instance using Terraform. This step-by-step guide empowers you to automate the creation and management of your cloud infrastructure, paving the way for efficient, consistent, and scalable tech operations.

--

--

Inzamam Ahmad

Write about DevOps, Cloud and Blockchain. Daily digest for tech learners 🤞