Getting Started with Terraform: Automating AWS Infrastructure
What Is Terraform? It is a tool from HashiCorp, and its primary purpose is to manage the infrastructure on the cloud. It's also called as Infrastructure as a code(IaC). Terraform has become a default standard for cloud automation, and today's time it can manage almost all the cloud providers like AWS, Azure, Google Cloud, Oracle Cloud, even Docker, and even Kubernetes. How Does It Look? Terraform code is structured and declarative, similar to JSON or YAML, but with its own HCL (HashiCorp Configuration Language) syntax. Here’s an example of a simple Terraform configuration: provider "aws" { region = "us-east-1" } resource "aws_instance" "web" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" tags = { Name = "WebServer" } } Breakdown: Provider Block: Specifies the cloud provider (AWS, Azure, etc.) and its configurations. Resource Block: Defines the infrastructure resource (e.g., an EC2 instance). Attributes: Properties like ami, instance_type, and tags configure the resource. After writing this, running terraform apply provisions the instance. Terraform ensures that the infrastructure matches the defined state, making it a powerful tool for Infrastructure as Code (IaC). To get started, install Terraform by following the official installation guide here. To check the version to ensure it's installed, run: terraform --version Setting Up AWS Access for Terraform Breakdown: Go to your AWS account and create an IAM user. Save the access key on your device. Ok Let's Begin: First log in to your AWS account search for IAM(Identify and Access Management) Go to users -> create user -> enter name -> next. For Set permissions select Attach policies directly -> Choose administratorAccess -> next and finally create user. Now User Is Created So Lets Create The Access Key: Click on the newly created username -> click on Security credentials tab. Find Create access key -> Click on Create access key -> Select Command Line Interface(CLI) -> Next -> Create the access key. Configure AWS CLI: Open Git Bash or any other terminal and run: Run aws configure. It will prompt you for an Access Key and Secret Key—paste them from your AWS account and keep the rest as default. Let's Start Writing Some Terraform Code. In this post, I'll cover how to find an amiId for an EC2 instance. Steps: Open your VS Code or any other code editor to start coding. create a file called instId.tf and paste the code given below. # The "data" block is used to fetch data from an existing resource # This block retrieves information about the latest Amazon Machine Image (AMI) for Ubuntu 22.04 data "aws_ami" "amiId" { most_recent = true # Ensures that the most recent AMI matching the filters is selected # First filter to match AMI names following a specific pattern filter { name = "name" values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"] # The wildcard (*) ensures it picks up all versions of Ubuntu 22.04 server AMIs } # Second filter to ensure the AMI uses HVM (Hardware Virtual Machine) virtualization filter { name = "virtualization-type" values = ["hvm"] } owners = ["099720109477"] # Specifies that the AMI must be owned by Canonical (official Ubuntu provider) } # Output block to display the fetched AMI ID output "instance_id" { description = "AMI ID of the instance" # Provides a description for the output value = data.aws_ami.amiId.id # Outputs the ID of the selected AMI } } Breakdown: Data Source Block (data "aws_ami" "amiId") Uses Terraform’s data block to query an existing AWS resource (AMI). Fetches the latest AMI that meets the specified filters. most_recent = true ensures the newest AMI is selected. Filtering AMI by Name filter { name = "name" } applies a filter based on the AMI name. values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]: Ensures that the AMI belongs to the Ubuntu 22.04 LTS (Jammy Jellyfish) Server series. The * wildcard picks up all minor versions. Filtering by Virtualization Type filter { name = "virtualization-type" } ensures that only HVM (Hardware Virtual Machine) AMIs are selected. values = ["hvm"]: HVM provides full virtualization and is required for most modern AWS instance types. Restricting to Official Ubuntu AMIs owners = ["099720109477"]: Specifies that the AMI must be owned by Canonical (Ubuntu’s official publisher). Prevents fetching AMIs from untrusted sources. Output Block (output "instance_id") Outputs the selected AMI ID so it can be referenced elsewhere in the Terraform configuration. description = "AMI ID of the instance" provides a human-readable explanation. value = data.aws_ami.amiId.id: Retrieves the id of the AMI selected from the data block. Useful for provisioning EC2 instances with the latest
![Getting Started with Terraform: Automating AWS Infrastructure](https://media2.dev.to/dynamic/image/width%3D1000,height%3D500,fit%3Dcover,gravity%3Dauto,format%3Dauto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl7r8hsiq4eah3ivm6j95.png)
What Is Terraform?
It is a tool from HashiCorp, and its primary purpose is to manage the infrastructure on the cloud.
It's also called as Infrastructure as a code(IaC).
Terraform has become a default standard for cloud automation, and today's time it can manage almost all the cloud providers like AWS, Azure, Google Cloud, Oracle Cloud, even Docker, and even Kubernetes.
How Does It Look?
Terraform code is structured and declarative, similar to JSON or YAML, but with its own HCL (HashiCorp Configuration Language) syntax. Here’s an example of a simple Terraform configuration:
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "WebServer"
}
}
Breakdown:
- Provider Block: Specifies the cloud provider (AWS, Azure, etc.) and its configurations.
- Resource Block: Defines the infrastructure resource (e.g., an EC2 instance).
- Attributes: Properties like
ami
,instance_type
, andtags
configure the resource.
After writing this, running terraform apply
provisions the instance. Terraform ensures that the infrastructure matches the defined state, making it a powerful tool for Infrastructure as Code (IaC).
To get started, install Terraform by following the official installation guide here.
To check the version to ensure it's installed, run:
terraform --version
Setting Up AWS Access for Terraform
Breakdown:
- Go to your AWS account and create an IAM user.
- Save the access key on your device.
Ok Let's Begin:
- First log in to your AWS account search for IAM(Identify and Access Management)
- Go to users -> create user -> enter name -> next.
- For Set permissions select Attach policies directly -> Choose administratorAccess -> next and finally create user.
Now User Is Created So Lets Create The Access Key:
- Click on the newly created username -> click on Security credentials tab.
- Find Create access key -> Click on Create access key -> Select Command Line Interface(CLI) -> Next -> Create the access key.
Configure AWS CLI:
Open Git Bash or any other terminal and run:
Run aws configure
. It will prompt you for an Access Key and Secret Key—paste them from your AWS account and keep the rest as default.
Let's Start Writing Some Terraform Code.
In this post, I'll cover how to find an amiId for an EC2 instance.
Steps:
- Open your VS Code or any other code editor to start coding.
- create a file called
instId.tf
and paste the code given below.
# The "data" block is used to fetch data from an existing resource
# This block retrieves information about the latest Amazon Machine Image (AMI) for Ubuntu 22.04
data "aws_ami" "amiId" {
most_recent = true # Ensures that the most recent AMI matching the filters is selected
# First filter to match AMI names following a specific pattern
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
# The wildcard (*) ensures it picks up all versions of Ubuntu 22.04 server AMIs
}
# Second filter to ensure the AMI uses HVM (Hardware Virtual Machine) virtualization
filter {
name = "virtualization-type"
values = ["hvm"]
}
owners = ["099720109477"]
# Specifies that the AMI must be owned by Canonical (official Ubuntu provider)
}
# Output block to display the fetched AMI ID
output "instance_id" {
description = "AMI ID of the instance" # Provides a description for the output
value = data.aws_ami.amiId.id # Outputs the ID of the selected AMI
}
}
Breakdown:
- Data Source Block (
data "aws_ami" "amiId"
)- Uses Terraform’s
data
block to query an existing AWS resource (AMI). - Fetches the latest AMI that meets the specified filters.
-
most_recent = true
ensures the newest AMI is selected.
- Uses Terraform’s
- Filtering AMI by Name
-
filter { name = "name" }
applies a filter based on the AMI name. -
values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
:- Ensures that the AMI belongs to the Ubuntu 22.04 LTS (Jammy Jellyfish) Server series.
- The
*
wildcard picks up all minor versions.
-
- Filtering by Virtualization Type
-
filter { name = "virtualization-type" }
ensures that only HVM (Hardware Virtual Machine) AMIs are selected. -
values = ["hvm"]
:- HVM provides full virtualization and is required for most modern AWS instance types.
-
- Restricting to Official Ubuntu AMIs
-
owners = ["099720109477"]
:- Specifies that the AMI must be owned by Canonical (Ubuntu’s official publisher).
- Prevents fetching AMIs from untrusted sources.
-
- Output Block (
output "instance_id"
)- Outputs the selected AMI ID so it can be referenced elsewhere in the Terraform configuration.
-
description = "AMI ID of the instance"
provides a human-readable explanation. -
value = data.aws_ami.amiId.id
:- Retrieves the
id
of the AMI selected from thedata
block. - Useful for provisioning EC2 instances with the latest Ubuntu AMI.
- Retrieves the
Running the Terraform Commands
Open your terminal in the same directory where the file is located and start typing the following commands:
-
terraform fmt
- It will check the format and fixes it if there is an issue.
- It will give a standard form.
-
terraform init
- This command reads all the
.tf
files in the current directory, checks the required resources, and downloads the necessary plugins from the Terraform registry.
- This command reads all the
-
terraform validate
- This command ensures that all the mentioned arguments and values are syntactically correct.
-
terraform plan
- This command creates an execution plan by comparing the current state with the desired configuration.
- It shows what changes Terraform will make without actually applying them.
- Helps in reviewing resource additions, modifications, or deletions before running terraform apply.
- Ensures there are no unexpected infrastructure changes.
-
terraform apply
- This command executes the planned changes to create, update, or delete resources as defined in the configuration.
- It prompts for confirmation before making any changes (unless -auto-approve is used).
- After successful execution, it provisions the infrastructure and displays the applied changes.
- Uses the Terraform state file to track managed resources.
Finally after apply is completed it prints out the output.
Conclusion
By following these steps, you can efficiently validate, plan, and apply your Terraform configurations to manage infrastructure. Ensuring proper validation and planning helps avoid unexpected changes and keeps your deployments smooth.