Provision EC2 Instance with EBS Volume using Terraform

Ankita LunawatAnkita Lunawat
5 min read

Terraform is an open-source infrastructure as code (IaC) tool developed by HashiCorp. It is used to define and provision infrastructure resources in a safe, repeatable, and automated way. Here’s a more detailed breakdown of what Terraform does and its key features:

Key Features of Terraform

  1. Infrastructure as Code (IaC):
    Terraform allows you to define your infrastructure using a high-level configuration language known as HashiCorp Configuration Language (HCL) or JSON. This approach allows you to manage infrastructure through version control, similar to application code.

  2. Declarative Configuration:
    With Terraform, you describe the desired state of your infrastructure, and Terraform automatically figures out the steps to reach that state from the current state. This contrasts with imperative configuration, where you manually define the steps needed to achieve the desired state.

  3. Resource Provisioning:
    Terraform supports a wide range of infrastructure providers, such as AWS, Azure, Google Cloud, VMware, and many others. It can provision and manage resources like virtual machines, storage, networking components, and more.

  4. Execution Plans:
    Before applying any changes, Terraform generates an execution plan that outlines what actions will be taken. This plan helps users understand what will happen if they apply the configuration, providing an opportunity to review and approve the changes.

  5. State Management:
    Terraform maintains a state file that represents the current state of the infrastructure. This state file is used to track resource changes over time and ensure that Terraform knows what resources exist, enabling it to apply only necessary changes.

  6. Modules:
    Terraform supports modules, which are reusable packages of Terraform configuration files. Modules allow you to create standard infrastructure components and share them across projects, promoting reusability and consistency.

  7. Multi-Cloud and Hybrid Cloud Support:
    Terraform's provider model allows it to work with multiple cloud providers and on-premises solutions, making it suitable for managing multi-cloud and hybrid cloud environments.

How Terraform Works

  • Write: You define infrastructure configurations using HCL in .tf files.

  • Plan: Terraform generates an execution plan to preview the changes that will be made to the infrastructure.

  • Apply: Terraform applies the execution plan to create, update, or delete resources to reach the desired state.

  • Destroy: When no longer needed, you can use Terraform to destroy the infrastructure it manages.

Use Cases

  • Cloud Infrastructure Management: Automating the provisioning and management of cloud resources like compute instances, networking, and storage.

  • Environment Consistency: Ensuring that development, testing, and production environments are consistent and reproducible.

  • Infrastructure Automation: Integrating Terraform with CI/CD pipelines to automate infrastructure provisioning and deployments.

  • Multi-Cloud Strategies: Managing resources across multiple cloud providers from a single configuration.

Terraform approach to managing infrastructure as code helps teams collaborate more effectively, reduce manual errors, and accelerate infrastructure provisioning .

Provision EC2 Instance with EBS Volume using Terraform

Prerequisites

- Terraform configuration is created to define an EC2 instance and a 3 GB EBS volume.

- The Terraform code is applied, and an EC2 instance is provisioned in your AWS account with the any AMI and instance type of your choice.

- An EBS volume of 3 GB is created. - The EBS volume is successfully attached to the EC2 instance.

Step 1: Verify the aws console

Log in to the AWS Management Console, navigate to the EC2 service, and verify that the EC2 instance is created.

Step 2: Configuring AWS IAM credentials with Permission

Search for “IAM” in the services search bar, select “IAM,” click on “Users” from the left-hand navigation pane, then click on the “Add user” button and enter a user name.

Set permissions by choosing "Attach policies directly," search for and select the 'AdministratorAccess' policy, click on the user, go to "Security credentials," and click on "Create access key," then select "Command Line Interface (CLI)."

After successfully creating the access key, you'll receive the credentials needed to set up AWS on your Windows machine.

Step 3: Install Terraform

Visit the Terraform downloads page - https://developer.hashicorp.com/terraform/install

We can follow below command to install terraform

wget-O-https://apt.releases.hashicorp.com/gpg|sudogpg--dearmor-o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo"deb[signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com$(lsb_release-cs)mainsudo/etc/apt/sources.list.d/hashicorp.list
sudo apt update 
sudo apt install terraform

Open a Command prompt and run the following command to verify Terraform is installed successfully -

terraform version

Step 4: To install the AWS CLI on Ubuntu

Update Your Package List

First, ensure your package list is up-to-date -

sudo apt update

The AWS CLI requires unzip and curl, so make sure these are installed.

sudo apt install unzip curl -y

Download the AWS CLI Bundle

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"

Unzip the Installation Bundle

unzip awscliv2.zip

Run the Install Script

Run the AWS CLI install script -

sudo ./aws/install

Verify the Installation

aws –version

Configure the AWS CLI

aws configure

Step 1: Create Terraform Configuration Files

Create ‘provider.tf’ file.

Open a text editor (e.g., Notepad, Visual Studio Code).

Create a new file named ‘provider.tf’ and add the following content.

Step 2: Write Your Terraform Configuration

Create a new file called main.tf and add the following code

# main.tf
# Specify the provider

provider "aws" {

region = "us-west-2" # Replace with your preferred region

}

# Create a new EC2 instance

resource "aws_instance" "example" {

ami           = "ami-0c55b159cbfafe1f0" # Replace with an appropriate AMI ID for your region

instance_type = "t2.micro"

tags = {

Name = "example-instance"

}

}

# Output the public IP of the instance

output "instance_public_ip" {

value = aws_instance.example.public_ip

}

Save the file in the directory.

3: Initialize and Apply Terraform Configuration.

 terraform init

2.Apply the Configuration.

terraform apply.

When prompted, type ‘yes’ to confirm.

Verify the EC2 instance and the creation of a 3GB EBS volume in AWS.

We have successfully executed the EBS volume is successfully attached to the EC2 instance.

Happy Learning…!

0
Subscribe to my newsletter

Read articles from Ankita Lunawat directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ankita Lunawat
Ankita Lunawat

Hi there! I'm a passionate AWS DevOps Engineer with 2+ years of experience in building and managing scalable, reliable, and secure cloud infrastructure. I'm excited to share my knowledge and insights through this blog. Here, you'll find articles on: AWS Services: Deep dives into core AWS services like EC2, S3, Lambda, and more. DevOps Practices: Best practices for CI/CD, infrastructure as code, and automation. Security: Tips and tricks for securing your AWS environments. Serverless Computing: Building and deploying serverless applications. Troubleshooting: Common issues and solutions in AWS. I'm always eager to learn and grow, and I hope this blog can be a valuable resource for fellow DevOps enthusiasts. Feel free to connect with me on [LinkedIn/Twitter] or leave a comment below!