Launching EC2 instance with terraform
Author: Duc Thai
Email: ducthai060501@gmail.com
Overview
Today we are going to start working with Terraform!
Here’s what we’re here to do:
- Understand the meaning behind the name:
"Terraform" originally means “to transform the atmosphere of a planet to make it habitable”—think of science fiction stories where Mars is made livable, or the machines in Superman trying to change Earth. - Apply that metaphor to cloud computing:
Instead of planets, we’ll be “terraforming” our AWS (or other cloud) accounts—making the cloud environment more suitable and structured for running our applications. - Learn about Terraform as a tool:
Terraform is a tool that helps us define, create, and manage infrastructure (like servers, networks, or databases) in a cloud account in a safe, repeatable, and automated way.
In summary:
We're here to learn how to make our cloud accounts (like AWS) ready for our applications—using Terraform as our tool for automated, codified infrastructure setup.
some intro about terraform
In this step, we are introducing the basics of Terraform’s configuration language and seeing what a typical Terraform file looks like.
What are we doing?
- Exploring the Terraform language:
- Terraform uses its own, simple configuration syntax that looks similar to JSON (technically, it's HashiCorp Configuration Language, or HCL).
- You define infrastructure as code using blocks like
resource, specify the type (e.g.,aws_instance), a resource name (likeweb01), and then all the required settings (likeami,instance_type, etc.) as arguments.
- Validating and formatting:
- You can check and format your code using commands like
terraform fmt(automatic formatting) andterraform validate(syntax and logical validation).
- You can check and format your code using commands like
- Understanding the workflow:
- Once you write your code, you run Terraform.
- Terraform will check if the resource (e.g., EC2 instance) already exists—if not, it creates it using the cloud provider’s API.
- The state and details of what’s created are stored in a special “state file” managed by Terraform, so your infrastructure is tracked.
Summary:
You're learning the fundamental structure of Terraform files, seeing real examples of resource blocks, and understanding how Terraform reads, formats, validates, and manages cloud infrastructure code—keeping everything tracked in its state.
Install terraform and aws set up
In this step, you are setting up your local development environment for using Terraform with AWS. Here’s exactly what you’re doing:
1. Installing Terraform
- Go to the official Terraform installation page.
- Download and install Terraform for your operating system (Windows, macOS, or Linux).
After installing, run:
terraform --versionto confirm Terraform is installed and see the version number.
2. Setting Up AWS CLI
- Make sure the AWS Command Line Interface (CLI) is installed on your machine.
Run:
aws configureand provide your AWS credentials (Access Key, Secret Key, region, etc.).
- This step lets both the AWS CLI and Terraform authenticate and manage cloud resources in your AWS account.
Summary:
You are preparing your environment by installing Terraform and configuring the AWS CLI so that you can provision and manage AWS resources using Terraform code in later steps.
Let's dive in
Launching EC2 with Terraform
Table of Contents
Finding AMI IDs
There are several ways to find Amazon Machine Image (AMI) IDs for your EC2 instances.
Method 1: AWS CLI
Use the AWS CLI command to find the latest Amazon Linux 2 AMI:
aws ec2 describe-images --owners amazon --filters "Name=name,Values=amzn2-ami-hvm-*-x86_64-gp2" --query "reverse(sort_by(Images, &CreationDate))[:1].ImageId" --output textMethod 2: AWS Console
- Go to EC2 Dashboard
- Navigate to Images → AMIs
- Search for "amzn2-ami-hvm-*-x86_64-gp2"
Method 3: Terraform Data Source
Use Terraform data source to get the latest AMI ID dynamically:
data "aws_ami" "amiID" {
most_recent = true
filter {
name = "name"
values = ["ami-0fa91bc90632c73c9"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
owners = ["amazon"]
}Terraform Basics
Data Sources
To get information outside Terraform, we use data sources.
Syntax:
data "TYPE" "NAME" {
CONFIG
}Data sources allow you to fetch information from your cloud provider or other external sources.
Output Blocks
Just like print in Python, output blocks are used to display values after terraform apply.
Syntax:
output "output_name" {
description = "Description of the output"
value = resource.type.name.attribute
}Basic Commands
Here are the essential Terraform commands you need to know:
| Command | Description |
|---|---|
terraform fmt | Format configuration files to canonical format |
terraform init | Initialize working directory and download provider plugins |
terraform validate | Validate configuration files for syntax errors |
terraform plan | Create an execution plan showing what actions Terraform will take |
terraform apply | Apply changes to reach the desired state of the configuration |
Command Details
- init: Reads configuration files in the current directory and downloads necessary provider plugins.
- plan: Creates an execution plan, showing what actions Terraform will take to achieve the desired state.
- apply: Applies the changes required to reach the desired state of the configuration.
Running Your First Script
Script Example
Create a file named main.tf with the following content:
data "aws_ami" "amiID" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
owners = ["099720109477"] # Canonical
}
output "instance_ami_id" {
description = "AMI ID of Ubuntu instance"
value = data.aws_ami.amiID.id
}What This Script Does
This script will output the latest Ubuntu 22.04 AMI ID using Terraform data sources.
Running the Commands
Execute the following commands in order:
terraform init
terraform plan
terraform applyExpected Output
ducth@DucPC MINGW64 ~/git_repos/quicksight-01/code/terraform/ex1 (main)
$ terraform apply
data.aws_ami.amiID: Reading...
data.aws_ami.amiID: Read complete after 0s [id=ami-0c846debef94e83c2]
Changes to Outputs:
+ instance_ami_id = "ami-0c846debef94e83c2"
You can apply this plan to save these new output values to the Terraform state,
without changing any real infrastructure.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
instance_ami_id = "ami-0c846debef94e83c2"Summary
Key Takeaways
- Terraform is an infrastructure as code tool that allows you to define and manage cloud resources.
- Basic Commands:
init,validate,plan,applyare the core commands for working with Terraform. - Data Sources are used to fetch information from outside Terraform (like AMI IDs from AWS).
- Output Blocks display values after
terraform apply, similar to print statements in programming. - AMI IDs can be found using AWS CLI, AWS Console, or Terraform data sources for dynamic retrieval.