Launch an EC2 Instance with Terraform
Provision and destroy an EC2 instance on AWS using Terraform code.
Introduction
30 Second Summary
Every time you click buttons in a cloud console to create a server, you're making changes that are impossible to track, repeat, or undo reliably. Imagine if you could describe your entire infrastructure in a file and create or destroy it with a single command.
In this project, you will use Terraform to launch an EC2 instance on AWS. You'll write configuration code from scratch and execute the full Terraform lifecycle to create and destroy cloud infrastructure on demand.
What You'll Build
A Terraform project that provisions an Amazon Linux 2023 EC2 instance in AWS, complete with outputs that display your instance's public IP and instance ID.
By the end of this project, you'll have:
- A working Terraform project with a main.tf and outputs.tf file that defines your cloud infrastructure as code.
- A running EC2 instance provisioned entirely through Terraform, visible in the AWS console.
- Hands-on experience with the full Terraform lifecycle: terraform init, terraform plan, terraform apply, and terraform destroy.
- Secret Mission: Add a security group that allows SSH access and connect to your instance remotely.
Are there any prerequisites?
You'll need an AWS account with IAM credentials (an access key ID and secret access key). If you don't have these yet, the project includes setup instructions in Step 1.
Before We Start
Before We Start...
Install Terraform and Configure AWS
Before you can define infrastructure as code, you need the tools that translate your code into real cloud resources.
In this step, you will install Terraform (the tool that reads your configuration and talks to AWS) and the AWS CLI (which stores your credentials so Terraform can authenticate).
In this step, get ready to:
- Install Terraform on Linux.
- Install the AWS CLI and verify it works.
- Configure your AWS credentials so Terraform can access your account.
Install Terraform
Terraform is the CLI tool that reads your .tf configuration files and creates the matching infrastructure in the cloud.
- Open your terminal.
- Check whether Terraform is already installed by running this command:
terraform version
✔️ I see a version number
You should see output starting with Terraform v followed by a version number. Terraform is ready to go.
ⓧ Command not found
Terraform is not installed yet. Install it using the HashiCorp APT repository by running these commands:
wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(grep -oP '(?<=UBUNTU_CODENAME=).*' /etc/os-release || lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update && sudo apt install terraform
What do these commands do?
- The first command downloads HashiCorp's GPG key so your system can verify the packages are authentic.
- The second command adds the HashiCorp package repository to your system's sources list.
- The third command updates your package index and installs Terraform.
- After installation completes, verify Terraform is installed by running:
terraform version
You should see output starting with Terraform v followed by a version number like 1.15.5.
Still seeing command not found?
- Make sure you ran all three commands in order. The sudo apt update step must complete before sudo apt install terraform can find the package.
- If you see a GPG error, check that wget is installed on your system. Try sudo apt install wget first, then re-run the commands.
Help me troubleshoot my Terraform installation on Linux.
Install the AWS CLI
The AWS CLI lets you interact with AWS services from your terminal. Terraform also uses the credentials stored by the AWS CLI to authenticate when creating resources.
- Check whether the AWS CLI is already installed by running:
aws --version
✔️ I see a version number
You should see output starting with aws-cli/ followed by a version number. The AWS CLI is ready.
ⓧ Command not found
The AWS CLI is not installed yet. Install it using snap by running:
sudo snap install aws-cli --classic
What does this command do?
This installs the official AWS-supported snap package of the AWS CLI. The --classic flag gives the snap full system access, which is required for the AWS CLI to read and write credential files.
- Verify the installation by running:
aws --version
You should see output starting with aws-cli/ followed by a version number.
Snap not available on your system?
If your Linux distribution does not support snap, you can install the AWS CLI manually using the bundled installer:
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
Help me install the AWS CLI on my Linux system.
Configure AWS credentials
Terraform needs permission to create resources in your AWS account. The simplest way to provide this is by storing your IAM credentials using the AWS CLI's configure command.
- Run the credential configuration wizard:
aws configure
The command will prompt you for four values. Enter them one at a time:
- AWS Access Key ID: paste your IAM access key ID.
- AWS Secret Access Key: paste your IAM secret access key.
- Default region name: enter us-east-1.
- Default output format: enter json.
Where do I find my Access Key ID and Secret Access Key?
These come from your IAM user in the AWS console. If you have not created them yet, go to the IAM service, select your user, open the Security credentials tab, and click Create access key.
Copy both values immediately. The secret access key is only shown once at creation time.
Why does Terraform use these credentials?
The AWS provider for Terraform automatically reads credentials from the same file the AWS CLI stores them in (~/.aws/credentials). You never need to hardcode keys in your Terraform files.
- Verify your credentials are working by running:
aws sts get-caller-identity
You should see a JSON response containing your AWS account number and user ARN. This confirms Terraform will be able to authenticate.
Seeing an authentication error?
- Double-check that you pasted your Access Key ID and Secret Access Key without any leading or trailing spaces.
- Make sure the IAM user has programmatic access enabled. Keys from users without CLI access will not work.
- Run aws configure again to re-enter your credentials if needed.
Help me fix my AWS CLI authentication error.
Your tools are installed and your credentials are configured. Next up, you will write your first Terraform configuration to define an EC2 instance.
Write Your Terraform Configuration
Your tools are ready. Now it's time to write the code that defines your infrastructure.
Terraform uses configuration files written in HCL (HashiCorp Configuration Language) to describe what you want to build. You will create two files: main.tf defines your infrastructure, and outputs.tf tells Terraform what information to display after building it.
In this step, get ready to:
- Create a project directory and configure the AWS provider.
- Define an EC2 instance resource in code.
- Create an outputs file to display your instance's information after deployment.
Create your project directory and provider configuration
Every Terraform project lives in its own directory. Terraform reads all .tf files in the working directory and treats them as a single configuration.
- Switch back to your terminal and move to your Desktop by running this command:
cd ~/Desktop
- Create your project folder and move into it by running these commands:
mkdir terraform-ec2
cd terraform-ec2
- Confirm the folder exists by running:
ls ~/Desktop | grep terraform-ec2
You should see terraform-ec2 in the output.
- Open your text editor.
- Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
- Type Cursor (or VS Code if that is what you installed) and press Enter to open it.
- Click File in the top menu bar.
- Click Open Folder.
- Select the terraform-ec2 folder on your Desktop, then click Open.
Now you are ready to create your first Terraform configuration file.
- Create a new file called main.tf in the terraform-ec2 folder and paste the following code into it:
# Tell Terraform which provider plugin to download
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
# Configure the AWS provider with your region
provider "aws" {
region = "us-east-1"
}
What does this code do?
The terraform block tells Terraform to download the AWS provider plugin from the Terraform Registry. The version constraint ~> 6.0 means any 6.x version is acceptable.
The provider block configures that plugin. Here you are telling the AWS provider to create resources in the us-east-1 region. Terraform automatically reads your AWS credentials from the ~/.aws/credentials file you configured in Step 1.
- Save main.tf.
You will not see a visible change yet. The next substep adds the resource that defines your EC2 instance.
File not saving?
Make sure you created main.tf inside the terraform-ec2 folder, not in a parent directory. The file extension must be .tf (not .txt or .tf.txt).
Help me troubleshoot creating my main.tf file in the correct location.
Define your EC2 instance resource
A resource block is where you define an actual piece of infrastructure. Each resource has a type (like aws_instance) and a name you choose (like my_ec2).
- In main.tf, add the following resource block below the provider block you just wrote:
# Define an EC2 instance
resource "aws_instance" "my_ec2" {
# Use the latest Amazon Linux 2023 AMI via SSM parameter
ami = "resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64"
# Free tier eligible instance size
instance_type = "t3.micro"
# Name tag visible in the AWS console
tags = {
Name = "MyTerraformInstance"
}
}
What does this code do?
The ami argument uses an SSM parameter to automatically resolve to the latest Amazon Linux 2023 AMI (Amazon Machine Image). This means your config always gets the most recent image without hardcoding a region-specific ID.
The instance_type is set to t3.micro, which is EC2 Free Tier eligible. The tags block gives your instance a name so you can identify it in the AWS console.
- Save main.tf.
- Confirm your file has all three blocks (terraform, provider, resource) by checking that the file is around 20 lines long.
Seeing a syntax highlighting error?
If your editor shows red underlines or warnings, make sure there is a blank line between each top-level block. Also check that every opening brace { has a matching closing brace }.
Help me fix syntax errors in my main.tf file.
✔️ Awesome, I've got everything!
Great. Make sure you have saved main.tf before continuing.
ⓧ I'd like to double check the full code
Here is the complete main.tf file for comparison:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "my_ec2" {
ami = "resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64"
instance_type = "t3.micro"
tags = {
Name = "MyTerraformInstance"
}
}
Create your outputs file
Terraform can display useful information after it finishes creating resources. You define these in an outputs.tf file.
- Create a new file called outputs.tf in the same terraform-ec2 folder and paste the following code into it:
# Display the instance ID after deployment
output "instance_id" {
description = "The ID of the EC2 instance"
value = aws_instance.my_ec2.id
}
# Display the public IP so you can access the instance
output "public_ip" {
description = "The public IP address of the EC2 instance"
value = aws_instance.my_ec2.public_ip
}
What does this code do?
Each output block tells Terraform to print a specific value after terraform apply finishes. The value field references attributes from the aws_instance.my_ec2 resource you defined in main.tf.
You will see your instance's ID and public IP address printed in the terminal after Terraform creates the instance in the next step.
- Save outputs.tf.
- In your terminal, confirm both files exist by running:
ls
You should see main.tf and outputs.tf listed in the output.
Only see one file?
Make sure you are still inside the terraform-ec2 directory. Run pwd to check your current location. If you accidentally created a file in the wrong directory, move it into terraform-ec2 or recreate it there.
Help me find my missing Terraform files.
✔️ Awesome, I've got everything!
Great. Make sure both files are saved before moving on.
ⓧ I'd like to double check the full code
Here is the complete outputs.tf file for comparison:
output "instance_id" {
description = "The ID of the EC2 instance"
value = aws_instance.my_ec2.id
}
output "public_ip" {
description = "The public IP address of the EC2 instance"
value = aws_instance.my_ec2.public_ip
}
Your Terraform configuration is complete. Next up, you will run the Terraform workflow to bring this infrastructure to life.
Deploy Your EC2 Instance
In the previous step, you wrote your complete Terraform configuration. Your main.tf describes the infrastructure you want, and outputs.tf defines what information you want to see after deployment.
Now it is time to execute. Terraform uses a three-command workflow to turn configuration into real infrastructure: initialize, plan, then apply. Each command gives you a checkpoint before anything changes in AWS.
In this step, get ready to:
- Run terraform init to download the AWS provider plugin.
- Run terraform plan to preview your infrastructure changes.
- Run terraform apply to launch your EC2 instance.
Initialize your Terraform project
Before Terraform can create anything, it needs to download the provider plugins your configuration requires. The terraform init command reads your main.tf and fetches the AWS provider.
- Initialize your Terraform project by running this command:
terraform init
What does this command do?
terraform init prepares your working directory for Terraform operations. It downloads the hashicorp/aws provider plugin into a hidden .terraform/ directory.
It also creates a .terraform.lock.hcl file that locks the exact provider version. This ensures consistent behavior if you share the project or run it again later.
- You should see output ending with Terraform has been successfully initialized! confirming the provider was downloaded.
- Confirm the lock file was created by running:
ls
- You should see main.tf, outputs.tf, and .terraform.lock.hcl in the output.
Seeing an error during init?
- If you see a network error, check your internet connection. Terraform needs to download the provider from the HashiCorp registry.
- If you see a provider version error, make sure your main.tf contains version = "~> 6.0" exactly as written in Step 2.
- help me debug a terraform init error
Preview your infrastructure plan
Before creating real resources, Terraform lets you preview exactly what it will do. This is like a dry run that shows you what will be created, changed, or destroyed.
- Preview the changes Terraform will make by running:
terraform plan
What does this output show?
The plan output uses symbols to indicate actions. A + create symbol means Terraform will create a new resource. You will see the full details of your aws_instance.my_ec2 resource listed with all its attributes.
At the bottom, the summary line Plan: 1 to add, 0 to change, 0 to destroy. confirms Terraform will create one resource and touch nothing else. Many values show as (known after apply) because AWS assigns them at creation time.
- Look for the Plan: 1 to add, 0 to change, 0 to destroy. line at the bottom of the output. This confirms your configuration is valid.
Plan shows errors instead of a summary?
- If you see a credentials error, your AWS CLI may not be configured correctly. Run aws configure again and double-check your Access Key ID and Secret Access Key.
- If you see a syntax error in main.tf, check for missing braces or quotation marks. Every opening { needs a closing }.
- help me fix a terraform plan error
Apply your configuration to launch the instance
The plan looked good. Now you will tell Terraform to actually create the EC2 instance in AWS. This is the command that makes real changes to your cloud account.
- Create your EC2 instance by running:
terraform apply
What happens when you run this?
Terraform will show you the same plan you saw before, then ask for confirmation. It prints Do you want to perform these actions? followed by Enter a value: where you type your answer.
Only typing yes will proceed. Any other input cancels the operation safely.
- When prompted with Enter a value:, type yes and press Enter.
- Wait for the instance to be created. You will see progress messages like aws_instance.my_ec2: Creating... followed by elapsed time updates.
- When finished, you should see Apply complete! Resources: 1 added, 0 changed, 0 destroyed. followed by your outputs listing the instance ID and public IP address.
What are those outputs?
The instance_id output shows the unique identifier AWS assigned to your EC2 instance (something like i-0abc123def456). The public_ip output shows the IP address your instance received.
These values come from the outputs.tf file you wrote in the previous step. Terraform automatically displays root module outputs after a successful apply.
- Now verify your instance is running in the AWS console. Open the AWS Management Console in your browser.
- Search for EC2 in the top search bar and select the EC2 service.
- Click Instances in the left sidebar.
- Make sure you are viewing the us-east-1 region (check the region dropdown in the top-right corner).
- You should see an instance named MyTerraformInstance with a status of Running.
Don't see your instance in the console?
- Check that you are in the us-east-1 region. The region selector is in the top-right corner of the console. Terraform created the instance in the region specified in your provider block.
- If the instance shows as Pending, wait a minute and refresh the page. EC2 instances take a short time to fully start.
- If you do not see any instance, confirm that terraform apply completed successfully with the Apply complete! message in your terminal.
- help me find my EC2 instance in the AWS console
Your EC2 instance is live. You just turned a text file into running cloud infrastructure. Next, you will look at how Terraform tracks this infrastructure and learn how to tear it all down with a single command.
Secret mission
Add SSH Access with a Security Group
Your EC2 instance is running, but you can't actually log into it. In this secret mission, you'll create a security group that opens port 22 for SSH, generate your own SSH key pair, and connect to your instance from your terminal.
Clean Up Your Resources
Clean Up Your Resources
Decide whether to keep your resources running, pause them to come back later, or delete them entirely.
The t3.micro instance is Free Tier eligible for most AWS accounts. If your Free Tier has expired, the instance costs approximately $0.0104/hour in us-east-1.
Cost warning
If your AWS Free Tier has expired and you re-deploy this infrastructure, the EC2 instance will incur charges until you run terraform destroy. Always destroy your resources when you finish working.
Resources you used:
- AWS resources managed by Terraform: EC2 instance (MyTerraformInstance), security group (terraform-ssh-access), and key pair (terraform-key).
- Local Terraform project files: main.tf, outputs.tf, terraform.tfstate, .terraform.lock.hcl, and the .terraform/ directory.
- SSH key pair at ~/.ssh/terraform-key and ~/.ssh/terraform-key.pub.
- AWS credentials stored at ~/.aws/credentials and ~/.aws/config.
- Terraform (installed via APT).
- AWS CLI (installed via snap).
Keep everything running
No action needed. Choose this if you plan to continue experimenting with your Terraform project or want to re-deploy your EC2 instance soon.
- Your local project files remain ready for another terraform apply whenever you want to spin up infrastructure again.
- Terraform and the AWS CLI stay installed on your machine for future projects.
- Your AWS credentials at ~/.aws/ remain configured for any AWS work.
- If you still have AWS resources running (you skipped terraform destroy earlier), be aware they consume Free Tier hours or incur charges.
Pause - I'll come back to this later
Destroy your AWS resources to stop any potential charges, but keep your local files so you can re-deploy later.
- If you still have AWS resources running, navigate to your project folder and run:
terraform destroy
- Type yes when prompted to confirm.
- If you already ran terraform destroy during the project, no further action is needed. Your local files are still intact for next time.
- When you are ready to resume, run terraform apply from the same folder to recreate everything.
Delete - I don't want to use this again
Remove all project resources, local files, and installed tools for a complete cleanup.
Destroy AWS resources
- If you have not already run terraform destroy, navigate to your project folder and run:
terraform destroy
- Type yes when prompted. This terminates your EC2 instance, security group, and key pair in AWS.
- If you already ran terraform destroy during the project, your AWS resources are already gone.
Delete local project files
- Navigate to your Desktop and delete your Terraform project folder (the folder containing main.tf and outputs.tf) by running:
cd ~/Desktop
rm -rf terraform-ec2
Folder name may differ
Replace terraform-ec2 with whatever you named your project folder when you created it in Step 2.
Delete SSH keys
- Remove the SSH key pair you generated for the Secret Mission by running:
rm ~/.ssh/terraform-key ~/.ssh/terraform-key.pub
Remove AWS credentials
- Delete your locally stored AWS credentials by running:
rm -rf ~/.aws
Only do this if you have no other AWS projects
The ~/.aws/ directory stores credentials for all AWS CLI usage on your machine. If you use AWS for other projects, skip this step and leave your credentials in place.
Uninstall Terraform
- Remove Terraform from your system by running:
sudo apt purge --auto-remove terraform
Uninstall AWS CLI
- Remove the AWS CLI by running:
sudo snap remove aws-cli
That's a Wrap!
That's a Wrap!
Nice work! You just provisioned cloud infrastructure entirely with code.
Instead of clicking through the AWS console, you defined your infrastructure in a main.tf file and managed its entire lifecycle from the terminal.
You've learned how to:
- Installed and configured Terraform with the AWS provider to manage cloud resources from your terminal.
- Wrote a complete Terraform configuration to define an EC2 instance, including outputs for the instance ID and public IP.
- Executed the full Terraform lifecycle: terraform init, terraform plan, terraform apply, and terraform destroy.
- Added SSH access with a security group and key pair, then connected to your instance from the terminal.
Ready to quiz yourself?