Overview:
Managing cloud infrastructure manually can be tedious and prone to errors, especially when working with multiple resources. Terraform is an open-source Infrastructure as Code (IaC) tool that allows you to define and provision your infrastructure with code, making the process reproducible and scalable. In this blog, we’ll walk through a simple example of using Terraform to provision an EC2 instance on AWS.
By the end of this guide, you will have a working EC2 instance deployed on AWS using Terraform, with all code provided.
Prerequisites:
- AWS Account.
- Basic understanding of AWS EC2 instances.
- Installed Terraform on your machine (instructions here).
- Installed AWS CLI and configured with your credentials (if you haven’t done this, check Day 1 of the blog series).
Step 1: Set Up a Terraform Project
Create a new directory for your Terraform project and navigate to it:
mkdir terraform-ec2
cd terraform-ec2
Create a file named main.tf
. This is where we will define our Terraform configuration.
touch main.tf
Step 2: Writing the Terraform Configuration
Add the following content to the main.tf
file. This file will define the AWS provider, specify the region, and create an EC2 instance.
# main.tf
# 1. Specify the Terraform provider (AWS)
provider "aws" {
region = "us-east-1" # Change this to your preferred region
}
# 2. Define an EC2 instance
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0" # Amazon Linux 2 AMI ID
instance_type = "t2.micro" # Free-tier eligible instance type
# Add tags to the instance
tags = {
Name = "My-Terraform-EC2"
}
}
# 3. Output the public IP of the instance
output "instance_public_ip" {
value = aws_instance.example.public_ip
}
Explanation:
- Provider: The
provider
block specifies that we are using AWS as our provider and sets the region where resources will be created. - Resource: The
aws_instance
block creates an EC2 instance using the Amazon Linux 2 AMI. The instance type ist2.micro
, which is eligible for the AWS free tier. - Output: This block outputs the public IP address of the instance, which is useful for connecting to the instance later.
Step 3: Initialize Terraform
Before you can run Terraform commands, you need to initialize your project. This downloads the necessary provider plugins (AWS in this case).
Run the following command in your project directory:
terraform init
You should see output similar to this:
Initializing the backend...
Initializing provider plugins...
- Finding hashicorp/aws versions matching ">= 2.0.0"...
- Installing hashicorp/aws v4.0.0...
- Installed hashicorp/aws v4.0.0 (signed by HashiCorp)
Terraform has been successfully initialized!
Step 4: Plan the Infrastructure
Next, let’s see what Terraform plans to create without actually deploying anything. The terraform plan
command checks your configuration and shows you the actions that will be taken.
Run the command:
terraform plan
If everything is correct, Terraform will show you a summary of the resources that will be created:
Plan: 1 to add, 0 to change, 0 to destroy.
Step 5: Apply the Configuration (Deploy the EC2 Instance)
Now it’s time to deploy the EC2 instance. Run the following command:
terraform apply
Terraform will show the resources that will be created and ask for confirmation. Type yes
to proceed.
Terraform will perform the following actions:
# aws_instance.example will be created
+ resource "aws_instance" "example" {
+ ami = "ami-0c55b159cbfafe1f0"
+ instance_type = "t2.micro"
+ tags = {
+ "Name" = "My-Terraform-EC2"
}
+ public_ip = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
Once the process is complete, Terraform will return the public IP address of your instance:
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Outputs:
instance_public_ip = "54.210.123.456"
You can now connect to your EC2 instance using SSH.
ssh [email protected] -i /path/to/your/private-key.pem
Replace the IP address with the one Terraform provided and use your own private key to connect to the instance.
Step 6: Managing Infrastructure
One of the key benefits of Terraform is its ability to manage infrastructure state. When you run terraform apply
, Terraform saves the state of your infrastructure in a terraform.tfstate
file. This allows Terraform to track what resources it created and update or destroy them if necessary.
For example, if you want to stop and destroy the EC2 instance you created, simply run:
terraform destroy
Terraform will ask for confirmation before destroying the instance:
Plan: 0 to add, 0 to change, 1 to destroy.
Type yes
to destroy the instance.
Step 7: Extending the Configuration (Optional)
Terraform is highly extensible, and you can easily add more resources to your configuration. Here are a few examples of what you can add:
7.1 Security Group
You might want to secure your EC2 instance by adding a security group that allows traffic only on port 22 (SSH). Add the following block to main.tf
to create a security group:
# Define a security group that allows SSH
resource "aws_security_group" "allow_ssh" {
name = "allow_ssh"
description = "Allow SSH inbound traffic"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"] # Be careful with 0.0.0.0/0 in production
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
Now, attach the security group to your EC2 instance by updating the aws_instance
resource:
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
# Attach the security group
vpc_security_group_ids = [aws_security_group.allow_ssh.id]
tags = {
Name = "My-Terraform-EC2"
}
}
After updating the configuration, run terraform apply
again to apply the changes.
Conclusion
In this tutorial, you learned how to use Terraform to automate the provisioning of an EC2 instance on AWS. We started with a simple EC2 instance, configured an output to display the public IP, and extended the configuration to add a security group. Terraform allows you to manage your infrastructure as code, making it easy to deploy, modify, and destroy cloud resources.
Terraform can be used for much more than just EC2 instances. You can manage entire cloud infrastructures, including networking, databases, storage, and more. In future tutorials, we can explore more advanced topics such as deploying complex multi-tier applications, using modules, and integrating with other services like RDS and S3.
Feel free to copy the provided code, modify it as needed, and try it out on your own AWS account!