Step-by-step guide to provision an AWS EC2 instance using Terraform:
Step 1: Install AWS CLI
- Download and install AWS CLI from here.
- Configure your AWS profile:
aws configure
- Enter your AWS Access Key ID, Secret Access Key, default region, and output format when prompted.
Step 2: Export AWS Credentials
- If you prefer to set environment variables manually, run:
export AWS_ACCESS_KEY_ID=<your_access_key>
export AWS_SECRET_ACCESS_KEY=<your_secret_key>
- Replace
<your_access_key>
and<your_secret_key>
with your actual AWS credentials.
Step 3: Install Terraform
- Download Terraform from here and install it according to your OS instructions.
- Verify installation:
terraform -version
Step 4: Create a Terraform Configuration File
- Open your favorite text editor and create a new file named
main.tf
. - Copy and paste the following code into
main.tf
:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "aws_ec2_test" {
count = 4
ami = "ami-08c40ec9ead489470"
instance_type = "t2.micro"
tags = {
Name = "TerraformTestServerInstance"
}
}
Step 5: Initialize Terraform
- Open your terminal, navigate to the directory containing
main.tf
, and run:
terraform init
- This installs necessary provider plugins.
Step 6: Review the Terraform Plan
- To see what Terraform will do before actually creating resources, run:
terraform plan
Step 7: Apply the Configuration
- To create the EC2 instances, run:
terraform apply
- You will see a plan; confirm by typing
yes
.
Step 8: Wait for Resources to be Created
- Terraform will now create 4 EC2 instances based on your configuration.
Step 9: Managing and Destroying Resources
- To delete the created resources later, run:
terraform destroy
- Confirm with
yes
Top comments (0)