Deploying an EC2 Instance Using Terraform
Introduction to Terraform Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp. It enables users to define, provision, and manage infrastructure using a declarative configuration language. With Terraform, infrastructure can be treated as code, making deployments more consistent, scalable, and automated. Why Use IaC Instead of AWS Management Console? Using the AWS Management Console for creating EC2 instances is straightforward but not scalable. It involves manual effort, which can lead to errors and inconsistencies. With IaC tools like Terraform, you can: Automate infrastructure provisioning Maintain consistent deployments Easily manage infrastructure versions Reuse code for different environments Reduce human errors Prerequisites Before we proceed ensure that you have: AWS Account - Sign up for an AWS Account Terraform Installed - Installation Guide AWS CLI Installed - Installation Guide AWS Configuration - Configure AWS credentials using the following command: aws configure You will be prompted to enter: AWS Access Key ID AWS Secret Access Key Default region name Default output format Terraform Best Practices Use Version Control: Store Terraform configurations in Git for tracking changes. Use Remote State: Store Terraform state files in a remote backend (like S3) to enable collaboration. Use Variables: Avoid hardcoding values; use variables.tf for flexibility. Modularize Code: Break down large configurations into reusable modules. Follow Least Privilege Principle: Provide only necessary permissions to resources. Terraform Configuration Files In this section, I'm following best practices by structuring the Terraform configuration into separate files. While it is possible to integrate all the code into a single file, breaking it into multiple files makes it easier to read, update, and manage changes effectively. This modular approach enhances maintainability and reusability. main.tf - Defines the EC2 Instance Resource This file defines the EC2 instance resource: resource "aws_instance" "ec2" { ami = var.ami_id instance_type = var.instance_type tags = { Name = var.instance_name timestamp = timestamp() } } Explanation: aws_instance "ec2" - Declares an EC2 instance. ami - Specifies the Amazon Machine Image ID. instance_type - Defines the type of EC2 instance. tags - Adds metadata to identify the instance. provider.tf - Configures the AWS Provider This file specifies the Terraform AWS provider: terraform { required_providers { aws = { source = "hashicorp/aws" version = "~> 4.16" } } required_version = ">= 1.2.0" } provider "aws" { region = var.region } Explanation: Defines AWS as the required provider. Specifies the provider source and version. Defines the AWS region from the variables.tf file. variables.tf - Defines Input Variables This file defines input variables: variable "region" { description = "AWS region where resources will be created" type = string default = "us-east-2" } variable "ami_id" { description = "AMI ID for the EC2 instance" type = string default = "ami-0c7c4e3c6b4941f0f" } variable "instance_type" { description = "EC2 instance type" type = string default = "t2.micro" } variable "instance_name" { description = "Name tag for the EC2 instance" type = string default = "Instance-01" } Explanation: Defines region, ami_id, instance_type, and instance_name as variables. Provides default values for each variable. outputs.tf - Captures Outputs After Execution This file captures outputs after Terraform execution: output "instance_id" { description = "ID of the created EC2 instance" value = aws_instance.ec2.id } output "public_ip" { description = "Public IP of the EC2 instance" value = aws_instance.ec2.public_ip } Explanation: Outputs the instance_id and public_ip after resource creation. Running Terraform After creating the necessary files, follow these steps to deploy the EC2 instance: 1. Initialize Terraform terraform init Explanation: Downloads necessary provider plugins. Prepares the working directory for Terraform commands. 2. Validate Configuration terraform validate Explanation: Checks if the configuration syntax is correct. Ensures all required fields are specified. 3. Plan Execution terraform plan Explanation: Shows what Terraform will create without applying changes. Helps verify expected modifications before execution. 4. Apply Configuration terraform apply Explanation: Deploys resources as per the configuration. Prompts for confirmation before executing. Once confirmed, creates the EC2 instance.
Introduction to Terraform
Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp. It enables users to define, provision, and manage infrastructure using a declarative configuration language. With Terraform, infrastructure can be treated as code, making deployments more consistent, scalable, and automated.
Why Use IaC Instead of AWS Management Console?
Using the AWS Management Console for creating EC2 instances is straightforward but not scalable. It involves manual effort, which can lead to errors and inconsistencies. With IaC tools like Terraform, you can:
- Automate infrastructure provisioning
- Maintain consistent deployments
- Easily manage infrastructure versions
- Reuse code for different environments
- Reduce human errors
Prerequisites
Before we proceed ensure that you have:
- AWS Account - Sign up for an AWS Account
- Terraform Installed - Installation Guide
- AWS CLI Installed - Installation Guide
- AWS Configuration - Configure AWS credentials using the following command:
aws configure
You will be prompted to enter:
- AWS Access Key ID
- AWS Secret Access Key
- Default region name
- Default output format
Terraform Best Practices
- Use Version Control: Store Terraform configurations in Git for tracking changes.
- Use Remote State: Store Terraform state files in a remote backend (like S3) to enable collaboration.
-
Use Variables: Avoid hardcoding values; use
variables.tf
for flexibility. - Modularize Code: Break down large configurations into reusable modules.
- Follow Least Privilege Principle: Provide only necessary permissions to resources.
Terraform Configuration Files
In this section, I'm following best practices by structuring the Terraform configuration into separate files. While it is possible to integrate all the code into a single file, breaking it into multiple files makes it easier to read, update, and manage changes effectively. This modular approach enhances maintainability and reusability.
main.tf
- Defines the EC2 Instance Resource
This file defines the EC2 instance resource:
resource "aws_instance" "ec2" {
ami = var.ami_id
instance_type = var.instance_type
tags = {
Name = var.instance_name
timestamp = timestamp()
}
}
Explanation:
-
aws_instance "ec2"
- Declares an EC2 instance. -
ami
- Specifies the Amazon Machine Image ID. -
instance_type
- Defines the type of EC2 instance. -
tags
- Adds metadata to identify the instance.
provider.tf
- Configures the AWS Provider
This file specifies the Terraform AWS provider:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = var.region
}
Explanation:
- Defines AWS as the required provider.
- Specifies the provider source and version.
- Defines the AWS region from the
variables.tf
file.
variables.tf
- Defines Input Variables
This file defines input variables:
variable "region" {
description = "AWS region where resources will be created"
type = string
default = "us-east-2"
}
variable "ami_id" {
description = "AMI ID for the EC2 instance"
type = string
default = "ami-0c7c4e3c6b4941f0f"
}
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t2.micro"
}
variable "instance_name" {
description = "Name tag for the EC2 instance"
type = string
default = "Instance-01"
}
Explanation:
- Defines
region
,ami_id
,instance_type
, andinstance_name
as variables. - Provides default values for each variable.
outputs.tf
- Captures Outputs After Execution
This file captures outputs after Terraform execution:
output "instance_id" {
description = "ID of the created EC2 instance"
value = aws_instance.ec2.id
}
output "public_ip" {
description = "Public IP of the EC2 instance"
value = aws_instance.ec2.public_ip
}
Explanation:
- Outputs the
instance_id
andpublic_ip
after resource creation.
Running Terraform
After creating the necessary files, follow these steps to deploy the EC2 instance:
1. Initialize Terraform
terraform init
- Downloads necessary provider plugins.
- Prepares the working directory for Terraform commands.
2. Validate Configuration
terraform validate
- Checks if the configuration syntax is correct.
- Ensures all required fields are specified.
3. Plan Execution
terraform plan
- Shows what Terraform will create without applying changes.
- Helps verify expected modifications before execution.
4. Apply Configuration
terraform apply
- Deploys resources as per the configuration.
- Prompts for confirmation before executing.
- Once confirmed, creates the EC2 instance.
4. Remove Resources
terraform destroy
⚠️ Please make sure to destroy resource if you don't want it anymore otherwise you will be charged.
Conclusion
We can use Terraform to deploy an EC2 instance automates the process, ensuring consistency and scalability. By following best practices, using variables, and leveraging IaC principles, managing cloud infrastructure becomes more efficient and reliable.