Infrastructure as Code (IaC) tools like Terraform streamline automation, especially when managing complex cloud deployments with numerous resources. This blog dives into how Terraform simplifies launching multiple EC2 instances in a single step.
Targeting Audience:
- This guide is ideal for anyone new to AWS who wants to create or launch multiple EC2 instances efficiently.
- It’s also valuable for those familiar with Terraform seeking to leverage the
count
argument for effortless multi-instance deployments.
Prerequisites to launch Multiple EC2 Instances Terraform:
- An active AWS account
- Terraform installed (we’ll use version 1.0.8)
- A code editor supporting HCL (Terraform’s language). Visual Studio Code is recommended.
Step-by-Step Guide:
To use Terraform to deploy multiple instances :
- Setting Up Terraform Configuration:
- Create a directory named
terraform-count-ec2-demo
and navigate to it using your terminal. - Within this directory, create three files:
main.tf
,vars.tf
, andprovider.tf
.
- Configuring
main.tf
:
resource "aws_instance" "my-machine" {
count = 4 # Launches four identical EC2 instances
ami = lookup(var.ec2_ami, var.region)
instance_type = var.instance_type
tags = {
Name = "my-machine-${count.index}" # Names instances based on their index (0-3)
}
}
count = 4
specifies launching four EC2 instances.lookup
retrieves the AMI ID based on region from theec2_ami
variable.count.index
dynamically assigns unique names to each instance.
- Defining Variables in
vars.tf
:
variable "ec2_ami" {
type = map
default = {
us-east-2 = "ami-0416962131234133f"
us-west-1 = "ami-006fce872b320923e"
}
}
variable "region" {
default = "us-east-2"
}
variable "instance_type" {
type = string
}
- This defines variables for AMI ID (mapped by region), region, and instance type.
- Configuring Provider in
provider.tf
:
provider "aws" {
region = "us-east-2"
}
- This sets the AWS provider region to
us-east-2
.
- Specifying Instance Type in
terraform.tfvars
:
instance_type = "t2.micro"
- This defines the instance type for the EC2 instances.
Running Terraform Commands:
- Initialize Terraform:
terraform init
- Preview the Deployment Plan:
- Bash
terraform plan
- Launch the EC2 Instances:
terraform apply
Verifying Deployment on AWS Console:
- Log in to your AWS Management Console.
- Navigate to the EC2 service.
- You should see four successfully launched EC2 instances with unique names matching the
count.index
pattern.
Conclusion:
This guide demonstrated launching multiple EC2 instances in AWS using Terraform’s count
functionality. With Terraform, managing and automating cloud infrastructure deployments becomes significantly simpler.
Ready to explore further? Consider integrating Terraform with your Squadcast account for streamlined configuration management.