Configure Your Cloud Infrastructure using Terraform and AWS CLI: A Step-by-Step Tutorial
Introduction
In this tutorial, you will learn how to set up an EC2 instance on Amazon Web Services (AWS) using Terraform and the AWS CLI. EC2 instances are virtual machines that run on AWS and are widely used in cloud infrastructure projects.
Prerequisites
To follow along with this tutorial, ensure you have:
Terraform CLI (version 1.2.0 or later) installed
AWS CLI installed
An AWS account with the necessary credentials to create resources
IAM credentials configured using environment variables or AWS CLI
Step 1: Configure AWS Credentials
Log into your AWS portal.
Click on your username in the top-right corner and select Security Credentials.
Under Access Keys, click Create access key.
Check the "I Understand" box and click Create.
Copy the Access Key and Secret Key.
Configure AWS CLI
Open your terminal and enter:
- Run these command: terraform --version
- Second command: aws --version
Follow the prompts and enter your:
AWS Access Key ID
AWS Secret Access Key
Default region name (e.g., us-east-1)
Output format (e.g., json or table)
But in this case, I left it as default
Step 2: Set Up Your Terraform Project
Create a working directory and navigate into it:
mkdir terraformtask
Open a new file named main.tf in a text editor and add the following configuration:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "app_server" {
ami = "ami-830c94e3"
instance_type = "t2.micro"
tags = {
Name = "ExampleAppServerInstance"
}
}
Step 3: Initialize Terraform
Run the following command to initialize the directory and download required provider plugins:
Step 4: Format, Validate, and Apply Configuration
Before applying the configuration, format and validate the files:
terraform fmt
terraform validate
If validation passes, apply the configuration:
terraform apply
Type yes when prompted to confirm.
Step 5: Verify the Infrastructure
To check the current state of your infrastructure, run:
This command displays the details of the provisioned resources.
Conclusion
Congratulations! You have successfully deployed an EC2 instance using Terraform and AWS CLI. This process is the foundation for automating cloud infrastructure deployment.
For more information, explore the Terraform Registry and the AWS Provider Documentation.
Top comments (0)