Imagine you are working on a project that needs the following infrastructure:
- One virtual machine to run your application.
- One storage bucket to store files.
- One database to store application data.
- A network to connect everything.
You open your cloud provider's dashboard and start creating these resources manually.
Everything works fine.
Now imagine your company wants to create the same infrastructure for development, testing, and production environments.
You have to repeat the entire process.
What happens if someone forgets to configure a security rule? What if you need to recreate the same infrastructure in another region? What if you accidentally delete a resource?
Managing infrastructure manually becomes difficult as your application grows.
Wouldn't it be better if you could describe your infrastructure using code and let a tool create it automatically?
This is exactly the problem Terraform solves.
Terraform is an Infrastructure as Code (IaC) tool that allows us to define, provision, update, and destroy infrastructure using configuration files.
Instead of manually creating cloud resources, we describe what we need in code, and Terraform communicates with the cloud provider to make it happen.
In this article, we'll understand Terraform from scratch, explore its architecture, write our first Terraform configuration, provision an AWS resource, understand state files, variables, outputs, modules, and important Terraform commands.
Versions used in this article:
- Terraform CLI: 1.17.2.
- AWS Provider: HashiCorp AWS provider. Check the latest compatible version in the Terraform Registry.
- Configuration language: HCL2.
Table of contents
- What is Terraform?
- How Terraform works
- Your first Terraform configuration
- The Terraform command workflow
- Understanding Terraform state
- Input variables
- Output values
- Terraform modules
- Terraform taint and untaint
- Which one should I use?
- Common mistakes
- Quick recap
- Try it yourself
What is Terraform?
Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp.
It allows us to define infrastructure using configuration files and automatically provision that infrastructure through cloud provider APIs.
In simple words, instead of creating infrastructure manually through a cloud dashboard, we write code describing what infrastructure we need.
Terraform reads that code and creates the required resources.
For example, suppose Ravi wants to create an AWS S3 bucket.
Instead of opening the AWS console and creating the bucket manually, Ravi writes a Terraform configuration:
resource "aws_s3_bucket" "my_bucket" {
bucket = "ravi-terraform-demo-bucket"
}
Now Terraform can create the bucket using the AWS provider.
The important idea is that we describe the desired infrastructure, and Terraform figures out what operations are required to achieve that state.
Terraform is commonly used for:
- Creating virtual machines.
- Creating storage buckets.
- Creating virtual networks.
- Provisioning databases.
- Configuring security groups.
- Managing cloud infrastructure.
- Recreating infrastructure across environments.
The problem Terraform solves
Let's understand the problem with a practical example.
Suppose Meera is working on an application hosted on AWS.
She needs the following resources:
AWS CLOUD
|
+----------+----------+
| | |
v v v
EC2 VM S3 Bucket Database
|
v
Application
Without Infrastructure as Code, Meera might create each resource manually using the AWS console.
Now imagine her team needs the same infrastructure in three environments:
- Development.
- Testing.
- Production.
The team has to repeat the configuration process.
This creates several problems:
- Manual work: Creating resources repeatedly takes time.
- Human errors: Someone might forget an important configuration.
- Inconsistency: Development and production environments may have different configurations.
- Difficult maintenance: Updating infrastructure requires repeating manual operations.
- Poor reproducibility: Recreating the exact infrastructure becomes difficult.
Now introduce Terraform.
Instead of manually creating resources, we write their configuration once.
TERRAFORM CODE
|
|
+---------+---------+
| | |
v v v
DEV ENV TEST ENV PROD ENV
| | |
v v v
AWS AWS AWS
Resources Resources Resources
We can reuse the same configuration with different input values to provision different environments.
This makes infrastructure easier to manage, reproduce, and maintain.
What Infrastructure as Code means
Infrastructure as Code (IaC) is the practice of managing infrastructure through machine-readable configuration files instead of manually configuring everything.
Let's understand the difference.
Without IaC:
Developer
|
v
Open Cloud Console
|
v
Create Virtual Machine
|
v
Configure Network
|
v
Create Storage
|
v
Configure Security
With IaC:
Developer
|
v
Write Configuration Files
|
v
Terraform
|
v
Cloud Provider API
|
v
Infrastructure Created
The infrastructure configuration becomes code.
We can also store this code in GitHub, just like application source code.
This gives us several benefits:
- Version control: Track infrastructure changes.
- Reusability: Reuse existing configurations.
- Consistency: Create similar environments using the same configuration.
- Automation: Reduce repetitive manual operations.
- Collaboration: Multiple developers can work on infrastructure code.
- Reproducibility: Recreate infrastructure from configuration.
For example, if your application needs a new storage bucket, you can update the Terraform configuration and review the proposed infrastructure changes before applying them.
That's the main idea behind Infrastructure as Code.
How Terraform works
Now let's understand how Terraform communicates with cloud platforms.
Terraform does not directly know how to create every cloud resource.
For example, creating an AWS EC2 instance requires AWS-specific API calls.
Creating an Azure virtual machine requires Azure-specific API calls.
So how does Terraform handle different cloud platforms?
It uses something called Providers.
Providers and resources
A provider is a plugin that allows Terraform to communicate with a particular infrastructure platform or service.
Examples:
- AWS Provider.
- AzureRM Provider.
- Google Cloud Provider.
- Kubernetes Provider.
- Docker Provider.
Each provider exposes different resource types and data sources.
Resource
A resource represents an infrastructure object that Terraform manages.
For example:
-
aws_instance: AWS EC2 instance. -
aws_s3_bucket: AWS S3 bucket. -
azurerm_virtual_machine: Azure virtual machine. -
google_storage_bucket: Google Cloud Storage bucket.
Let's understand the relationship.
TERRAFORM
|
v
PROVIDER
|
+----------+----------+
| | |
v v v
AWS AZURE GCP
| | |
v v v
Resources Resources Resources
| | |
v v v
EC2, S3 VM, VNet VM, GCS
Terraform uses the provider plugin to communicate with the external platform.
The provider translates Terraform's requested operations into API requests that the platform understands.
For example:
Terraform Configuration
|
v
AWS Provider
|
v
AWS APIs
|
v
Create S3 Bucket
Without a provider, Terraform cannot manage resources specific to that platform.
Terraform and cloud platforms
Terraform supports many infrastructure platforms through its provider ecosystem.
Some popular integrations include:
- Amazon Web Services (AWS).
- Microsoft Azure.
- Google Cloud Platform (GCP).
- Kubernetes.
- Docker.
- VMware.
- Cloudflare.
It is important to understand that Terraform does not automatically support every service offered by every cloud provider.
The available resources and capabilities depend on the providers and their implementations.
You can discover providers through the Terraform Registry:
https://registry.terraform.io/
For example, if you want to work with AWS, you need the AWS provider.
If you want to work with Azure, you need the Azure provider.
The same Terraform workflow can be used across different platforms, but their provider configurations and resource definitions are different.
Understanding HCL
Terraform uses a configuration language called HCL.
HCL stands for HashiCorp Configuration Language.
It is a human-readable language designed for defining configuration.
Instead of writing complex programming logic, we describe the infrastructure we want.
For example:
resource "aws_s3_bucket" "my_bucket" {
bucket = "my-terraform-demo-bucket"
}
Let's understand the syntax.
resource "aws_s3_bucket" "my_bucket" {
| |
| |
v v
Resource Type Resource Name
}
-
resource: Declares an infrastructure resource. -
aws_s3_bucket: Specifies the type of resource. -
my_bucket: A name used to identify this resource inside Terraform. -
bucket: An argument provided to the AWS resource.
Notice that my_bucket is not the actual bucket name.
The actual bucket name is the value assigned to the bucket argument.
HCL supports different block types, including:
-
terraform: Terraform configuration. -
provider: Provider configuration. -
resource: Infrastructure resource. -
variable: Input variable. -
output: Output value. -
module: Module declaration. -
data: Data source.
We'll use these blocks throughout this article.
Your first Terraform configuration
Let's create our first practical Terraform project.
We'll create an AWS S3 bucket using Terraform.
An S3 bucket is a storage container in AWS that can store files and objects.
First, install Terraform and configure the AWS CLI on your machine.
Check the installation:
terraform version
Example output:
Terraform v1.17.2
on windows_amd64
Your operating system and architecture will determine the platform information shown.
Now create a project directory:
mkdir terraform-demo
cd terraform-demo
Create a file named:
main.tf
Terraform configuration files use the .tf extension.
Our project will initially look like this:
terraform-demo/
|
+-- main.tf
Add the following configuration to main.tf:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 5.0.0"
}
}
}
provider "aws" {
region = "ap-south-1"
}
resource "aws_s3_bucket" "my_bucket" {
bucket = "my-unique-terraform-demo-bucket-12345"
}
Replace the bucket name with a globally unique name.
Let's understand the configuration.
1. Terraform block
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 5.0.0"
}
}
}
This block tells Terraform which provider plugin is required.
Here:
-
awsis the local provider name. -
hashicorp/awsidentifies the provider source. -
versionspecifies the acceptable provider version range.
The provider version is separate from the Terraform CLI version.
2. Provider block
provider "aws" {
region = "ap-south-1"
}
This configures the AWS provider.
Here, ap-south-1 represents the Mumbai AWS region.
3. Resource block
resource "aws_s3_bucket" "my_bucket" {
bucket = "my-unique-terraform-demo-bucket-12345"
}
This declares an S3 bucket that Terraform should manage.
Now we have described the infrastructure we want.
But how will Terraform access our AWS account?
That's where authentication comes into the picture.
AWS authentication and access keys
To create AWS resources, Terraform needs permission to communicate with AWS APIs.
For example, if Terraform needs to create an S3 bucket, AWS must verify that the request comes from an authorized identity.
For local development, one common authentication method is AWS access keys.
An AWS access key consists of:
- Access Key ID.
- Secret Access Key.
Think of them as credentials that allow an application or tool to authenticate with AWS.
TERRAFORM
|
| AWS API Request
|
v
AWS PROVIDER
|
| Credentials
|
+------+------+
| |
v v
Access Key ID Secret Access Key
| |
+------+------+
|
v
AWS CLOUD
|
v
Authentication
|
v
API Operations
For example, you can configure AWS credentials using the AWS CLI:
aws configure
It will ask for:
AWS Access Key ID: YOUR_ACCESS_KEY_ID
AWS Secret Access Key: YOUR_SECRET_ACCESS_KEY
Default region name: ap-south-1
Default output format: json
Alternatively, you can configure environment variables.
For Linux or macOS:
export AWS_ACCESS_KEY_ID="YOUR_ACCESS_KEY_ID"
export AWS_SECRET_ACCESS_KEY="YOUR_SECRET_ACCESS_KEY"
export AWS_REGION="ap-south-1"
For PowerShell:
$env:AWS_ACCESS_KEY_ID="YOUR_ACCESS_KEY_ID"
$env:AWS_SECRET_ACCESS_KEY="YOUR_SECRET_ACCESS_KEY"
$env:AWS_REGION="ap-south-1"
Now the AWS provider can use these credentials without storing them directly in the Terraform configuration.
Important security note:
Never hardcode access keys inside .tf files or commit them to GitHub.
Also, access keys are not the only authentication method.
For production environments, prefer temporary credentials and IAM roles or other workload identity mechanisms where supported.
AWS authentication is specific to AWS. Azure and Google Cloud use their own authentication mechanisms.
The Terraform command workflow
Now that we have written our Terraform configuration, let's understand how to execute it.
Terraform provides several commands to manage infrastructure.
The most important commands are:
Write .tf Configuration
|
v
terraform init
|
v
terraform fmt
|
v
terraform validate
|
v
terraform plan
|
v
terraform apply
|
v
Infrastructure Created
|
v
terraform destroy
|
v
Infrastructure Deleted
Let's understand each command.
terraform init
The first command we execute in a new Terraform project is:
terraform init
The init command initializes the Terraform working directory.
But why do we need it?
Remember that Terraform uses providers to communicate with cloud platforms.
Our configuration uses the AWS provider.
Terraform needs to download and install that provider before it can manage AWS resources.
terraform init performs initialization tasks such as:
- Downloading required providers.
- Installing required modules.
- Initializing the configured backend.
- Preparing the working directory.
Run:
terraform init
Simplified example output:
Initializing the backend...
Initializing provider plugins...
- Finding hashicorp/aws versions matching ">= 5.0.0"...
- Installing hashicorp/aws...
- Installed hashicorp/aws successfully
Terraform has been successfully initialized!
The exact version and output will depend on the provider release selected by Terraform.
Behind the scenes
Terraform reads the provider requirements from the configuration.
It downloads the required provider plugin and stores the installation information in the .terraform directory.
It also creates or updates the dependency lock file:
.terraform.lock.hcl
This file records the selected provider versions and checksums.
You should commit .terraform.lock.hcl to version control so your team can use consistent provider selections.
terraform fmt and validate
After initialization, we should format and validate our configuration.
These commands solve two different problems.
1. terraform fmt
The fmt command automatically formats Terraform configuration files.
For example:
terraform fmt
It fixes formatting issues such as indentation and spacing.
You don't have to manually align every block.
To check formatting without changing files:
terraform fmt -check
2. terraform validate
The validate command checks whether the configuration is syntactically valid and internally consistent.
Run:
terraform validate
Example output:
Success! The configuration is valid.
But what exactly does validation check?
It checks things such as:
- Valid Terraform syntax.
- Correct block structure.
- Valid references.
- Required arguments.
- Configuration consistency.
One important distinction:
terraform validate does not verify that your AWS credentials work or that AWS will successfully create the resource.
That is why we have the next command.
terraform plan
This is one of the most important Terraform commands.
terraform plan
The plan command creates an execution plan.
It compares your desired infrastructure configuration with the current infrastructure and Terraform state.
It then displays what Terraform intends to do.
For example, suppose you have declared an S3 bucket:
resource "aws_s3_bucket" "my_bucket" {
bucket = "my-unique-terraform-demo-bucket-12345"
}
But the bucket does not exist yet.
Terraform will show a plan to create it.
Simplified output:
Terraform will perform the following actions:
# aws_s3_bucket.my_bucket will be created
+ resource "aws_s3_bucket" "my_bucket" {
+ bucket = "my-unique-terraform-demo-bucket-12345"
+ id = (known after apply)
+ arn = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
Let's understand the symbols:
+ Create a new resource
~ Update an existing resource
- Destroy an existing resource
-/+ Destroy and recreate a resource
+/- Create a replacement before destroying the old resource
The exact ordering of replacement symbols depends on the lifecycle operation.
The important point is that Terraform shows the proposed changes before making them.
Why is terraform plan important?
Imagine you accidentally change a configuration that causes an existing database to be destroyed.
If you directly execute an apply without reviewing the plan, you might make a destructive change.
With terraform plan, you can inspect the proposed changes first.
Think of it as a preview of infrastructure changes.
terraform apply
Once we are satisfied with the execution plan, we can apply it.
terraform apply
Terraform displays the proposed changes and asks for confirmation.
Example:
Plan: 1 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
Enter a value:
yes
After entering yes, Terraform communicates with AWS and creates the S3 bucket.
Simplified output:
aws_s3_bucket.my_bucket: Creating...
aws_s3_bucket.my_bucket: Creation complete
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Now the S3 bucket exists in AWS.
Behind the scenes
- Terraform reads the configuration.
- Terraform determines the required changes.
- The AWS provider receives the resource creation request.
- The provider communicates with AWS APIs.
- AWS creates the bucket.
- Terraform records the resource information in its state.
Notice that Terraform does not directly create the bucket itself.
The AWS provider communicates with AWS and performs the actual API operations.
terraform destroy
What happens when we no longer need the infrastructure?
For example, suppose Meera created an S3 bucket for testing and now wants to remove it.
We can use:
terraform destroy
Terraform calculates which managed resources should be deleted.
Example output:
Terraform will perform the following actions:
# aws_s3_bucket.my_bucket will be destroyed
Plan: 0 to add, 0 to change, 1 to destroy.
Do you really want to destroy all resources?
Enter a value:
After confirmation, Terraform asks the AWS provider to delete the bucket.
Simplified output:
aws_s3_bucket.my_bucket: Destroying...
aws_s3_bucket.my_bucket: Destruction complete
Destroy complete! Resources: 1 destroyed.
Important: AWS S3 buckets must be empty before they can normally be deleted. If the bucket contains objects, the destroy operation may fail until those objects are removed.
Also, terraform destroy deletes resources managed by the current Terraform configuration and workspace. Never execute it in a production environment without reviewing its plan carefully.
Understanding Terraform state
So far, we have learned how Terraform creates and destroys infrastructure.
But here's an interesting question.
Suppose Terraform created an S3 bucket yesterday.
Today, you execute:
terraform plan
How does Terraform know that the bucket already exists?
Does it recreate the bucket every time?
No.
Terraform maintains information about the infrastructure it manages using something called a State File.
The default local state file is:
terraform.tfstate
Why Terraform needs a state file
A state file is used by Terraform to maintain the relationship between resources declared in configuration and the actual infrastructure objects.
It contains information such as:
- Resource addresses.
- Resource IDs.
- Resource attributes.
- Provider information.
- Dependency-related information.
- Metadata needed to manage infrastructure.
Let's understand with an example.
Our Terraform configuration declares:
resource "aws_s3_bucket" "my_bucket" {
bucket = "my-unique-terraform-demo-bucket-12345"
}
After successfully creating the bucket, Terraform records information about that resource in its state.
Conceptually:
main.tf
|
|
v
TERRAFORM
|
| Create Resource
v
AWS CLOUD
|
v
S3 Bucket
|
|
v
terraform.tfstate
|
v
Resource Information
The state file helps Terraform identify which real-world resource corresponds to aws_s3_bucket.my_bucket.
Now suppose we execute:
terraform plan
Terraform uses the configuration, state, and refreshed information from the provider to determine whether any changes are required.
If the infrastructure already matches the desired configuration, Terraform generally reports:
No changes. Your infrastructure matches the configuration.
This is why the state file is so important.
Behind the scenes
Terraform uses three important pieces of information:
- Configuration: What infrastructure do we want?
- State: What infrastructure does Terraform currently manage?
- Real infrastructure: What actually exists in the cloud?
CONFIGURATION
(Desired State)
|
|
v
TERRAFORM
^
|
STATE FILE
(Known State)
|
|
v
CLOUD API
|
v
REAL INFRASTRUCTURE
Terraform compares these sources to determine what operations are required.
The state file is not simply a backup of your .tf files. It is an important record used to manage real infrastructure.
Local state vs remote state
By default, Terraform stores state locally in a file named:
terraform.tfstate
This is called local state.
It works well when you are learning Terraform or experimenting with a small project.
But imagine a team of five developers working on the same infrastructure.
If each developer has a separate local state file, their state information can become inconsistent.
For example:
- Developer A creates a virtual machine.
- Developer B does not know that it exists.
- Developer B applies another configuration using outdated state information.
This can create serious infrastructure management problems.
For team environments, we generally use remote state.
Remote state means storing Terraform state in a shared remote backend.
Examples include:
- Amazon S3 with appropriate locking configuration.
- HCP Terraform.
- Other supported remote backends.
DEVELOPER A
|
|
DEVELOPER B
|
|
DEVELOPER C
|
v
REMOTE STATE
|
v
SHARED STATE
Remote backends can also provide state locking, which helps prevent conflicting operations when multiple users try to modify the same state simultaneously.
Important security point:
Terraform state can contain sensitive information, including credentials or passwords returned by providers.
Never commit terraform.tfstate to a public GitHub repository.
For production environments, use a properly secured remote backend, access controls, encryption, and state locking where supported.
Input variables
So far, we have hardcoded the S3 bucket name directly inside our configuration.
resource "aws_s3_bucket" "my_bucket" {
bucket = "my-unique-terraform-demo-bucket-12345"
}
But what if we want to create different buckets for different environments?
For example:
Development -> dev-bucket
Testing -> test-bucket
Production -> prod-bucket
Do we need to modify the configuration every time?
No.
Terraform provides Input Variables.
Input variables allow us to pass values into our Terraform configuration instead of hardcoding them.
Let's create a file called:
variables.tf
Add:
variable "bucket_name" {
description = "Name of the S3 bucket"
type = string
default = "my-unique-terraform-demo-bucket-12345"
}
Now update main.tf:
resource "aws_s3_bucket" "my_bucket" {
bucket = var.bucket_name
}
Notice:
var.bucket_name
The var keyword is used to reference an input variable.
Now we can pass a different value without modifying the resource configuration.
For example:
terraform plan -var="bucket_name=my-dev-terraform-bucket-12345"
Or create a file named:
terraform.tfvars
Add:
bucket_name = "my-dev-terraform-bucket-12345"
Terraform automatically loads the default terraform.tfvars file.
Now execute:
terraform plan
Terraform uses the value from the variable file.
Behind the scenes
variables.tf
|
v
bucket_name
|
|
v
terraform.tfvars
|
v
"my-dev-bucket"
|
v
main.tf
|
v
aws_s3_bucket
Input variables make Terraform configurations reusable and configurable.
You can also declare variables with different types:
variable "environment" {
type = string
}
variable "instance_count" {
type = number
}
variable "enable_backup" {
type = bool
}
variable "availability_zones" {
type = list(string)
}
This helps Terraform validate the values passed into your configuration.
Output values
We have learned how to pass values into Terraform using input variables.
But what if Terraform creates a resource and we want to display some information about it?
For example:
- S3 bucket name.
- EC2 instance ID.
- Public IP address.
- Resource ARN.
Terraform provides Output Values for this purpose.
Output values allow us to expose information from resources and modules.
Let's create a file called:
outputs.tf
Add:
output "bucket_name" {
description = "Name of the created S3 bucket"
value = aws_s3_bucket.my_bucket.bucket
}
output "bucket_arn" {
description = "ARN of the created S3 bucket"
value = aws_s3_bucket.my_bucket.arn
}
Let's understand this:
aws_s3_bucket.my_bucket.bucket
This references the bucket attribute of the S3 resource.
Similarly:
aws_s3_bucket.my_bucket.arn
References the ARN attribute.
ARN stands for Amazon Resource Name. It is a unique identifier used to identify AWS resources.
Now execute:
terraform apply
After successful creation, Terraform displays the configured outputs.
Example:
Outputs:
bucket_name = "my-dev-terraform-bucket-12345"
bucket_arn = "arn:aws:s3:::my-dev-terraform-bucket-12345"
You can also retrieve outputs later using:
terraform output
Or retrieve a specific output:
terraform output bucket_name
Behind the scenes
AWS RESOURCE
|
v
Resource Attributes
|
v
outputs.tf
|
v
Output Values
|
v
terraform output
One important point:
Output values are not automatically secret.
If an output contains sensitive information, use sensitive = true and follow proper secret-handling practices.
Terraform modules
Now let's discuss one of the most useful concepts in Terraform.
Imagine your company has ten applications.
Every application needs:
- An S3 bucket.
- A security group.
- A virtual machine.
- A network configuration.
You could write the same Terraform resource definitions separately for every application.
But that creates duplicated code.
What if you need to change the configuration?
You would have to update it in multiple places.
Terraform solves this problem using Modules.
A module is a collection of Terraform configuration files grouped together to manage related infrastructure.
In simple words, a module is a reusable collection of Terraform code.
Think of it like a reusable component in React or a reusable class in Java.
Instead of writing the same logic repeatedly, you create it once and use it wherever required.
Terraform modules help us:
- Reuse infrastructure configurations.
- Avoid code duplication.
- Organize large Terraform projects.
- Standardize infrastructure.
- Separate infrastructure responsibilities.
Terraform has two important module concepts:
- Root Module.
- Child Module.
The root module is the main Terraform configuration directory where you execute Terraform commands.
A child module is another module called by the root module.
ROOT MODULE
|
+--------+--------+
| | |
v v v
NETWORK STORAGE COMPUTE
MODULE MODULE MODULE
| | |
v v v
VPC S3 EC2
Let's create a reusable module.
Create a reusable module
Suppose we want to create a reusable S3 bucket module.
Our project structure will look like this:
terraform-project/
|
+-- main.tf
|
+-- variables.tf
|
+-- outputs.tf
|
+-- modules/
|
+-- s3-bucket/
|
+-- main.tf
|
+-- variables.tf
|
+-- outputs.tf
Inside modules/s3-bucket/main.tf:
resource "aws_s3_bucket" "bucket" {
bucket = var.bucket_name
}
Inside modules/s3-bucket/variables.tf:
variable "bucket_name" {
description = "Name of the S3 bucket"
type = string
}
Inside modules/s3-bucket/outputs.tf:
output "bucket_arn" {
value = aws_s3_bucket.bucket.arn
}
output "bucket_name" {
value = aws_s3_bucket.bucket.bucket
}
We have now created a reusable module.
Notice that the module accepts a bucket name through an input variable and exposes the bucket information through output values.
This allows other Terraform configurations to reuse it.
Using a module
Now let's use our module from the root configuration.
Inside the root main.tf:
module "dev_bucket" {
source = "./modules/s3-bucket"
bucket_name = "my-dev-terraform-bucket-12345"
}
module "test_bucket" {
source = "./modules/s3-bucket"
bucket_name = "my-test-terraform-bucket-12345"
}
Here:
-
moduledeclares a module. -
dev_bucketis the module name. -
sourcespecifies where the module is located. -
bucket_namepasses an input variable to the module.
We are using the same module twice with different input values.
Now expose the module outputs from the root module.
Inside the root outputs.tf:
output "dev_bucket_arn" {
value = module.dev_bucket.bucket_arn
}
output "test_bucket_arn" {
value = module.test_bucket.bucket_arn
}
Notice the syntax:
module.dev_bucket.bucket_arn
This accesses an output value from the child module.
Now execute:
terraform init
terraform fmt
terraform validate
terraform plan
terraform apply
Terraform downloads or loads the module and provisions both S3 buckets.
Behind the scenes
ROOT MODULE
|
+------+------+
| |
v v
dev_bucket test_bucket
| |
v v
S3 MODULE S3 MODULE
| |
v v
DEV BUCKET TEST BUCKET
The same infrastructure logic is reused with different input values.
Modules can also be downloaded from the Terraform Registry, Git repositories, and other supported sources.
One important point: after changing a module's source or registry version, run terraform init again to update the module installation.
Terraform taint and untaint
Now let's understand two commands that are useful when managing resource health and replacement.
terraform taintterraform untaint
Imagine Terraform created an EC2 instance.
After some time, the instance becomes damaged or enters an unexpected state.
You want Terraform to recreate that instance.
Terraform has a concept called a tainted resource.
A tainted resource is a resource marked in Terraform state as needing replacement.
The modern replacement for taint
Historically, we could use:
terraform taint aws_instance.my_instance
This marks the specified resource as tainted.
During the next plan or apply, Terraform proposes replacing that resource.
However, terraform taint is now deprecated.
HashiCorp recommends using the -replace option instead.
For example:
terraform plan -replace="aws_instance.my_instance"
This previews the replacement operation.
If the plan looks correct, execute:
terraform apply -replace="aws_instance.my_instance"
Terraform will replace the specified instance.
This is safer because the replacement appears in the execution plan before you approve it.
What about terraform untaint?
The terraform untaint command removes the tainted marker from a resource in Terraform state.
For example:
terraform untaint aws_instance.my_instance
Why would we use it?
Imagine Terraform marked an instance as tainted, but after checking it, you discover that the instance is actually working correctly.
You can remove the tainted status using terraform untaint.
This does not repair or modify the actual cloud resource. It only changes the state information.
Remember:
-
terraform taint: Legacy command to mark a resource for replacement. Deprecated. -
terraform untaint: Removes the tainted marker from a resource. -
terraform apply -replace: Recommended modern way to request resource replacement.
Which one should I use?
Let's quickly compare the important Terraform concepts.
1. Configuration vs State
- Configuration (
.tf): Describes the desired infrastructure. - State (
terraform.tfstate): Records Terraform's knowledge of managed infrastructure.
You need both to manage infrastructure reliably.
2. Input Variables vs Output Values
- Input variables: Pass values into a configuration.
- Output values: Expose values from resources or modules.
Use input variables to make configurations reusable and output values to expose useful resource information.
3. Root Module vs Child Module
- Root module: Main Terraform working directory.
- Child module: Reusable Terraform configuration called by another module.
Start with a root module for small projects. Introduce child modules when you have infrastructure that needs to be reused or logically separated.
4. Local State vs Remote State
- Local state: Stored on your local machine.
- Remote state: Stored in a shared backend.
For learning, local state is fine. For team and production environments, use a secure remote backend with suitable locking support.
5. terraform taint vs -replace
-
terraform taint: Deprecated. -
terraform apply -replace: Recommended approach.
Prefer -replace because you can review the proposed replacement before applying it.
My recommended learning order:
1. Understand IaC
|
v
2. Learn HCL
|
v
3. Understand Providers and Resources
|
v
4. Learn Terraform Commands
|
v
5. Understand State Files
|
v
6. Learn Variables and Outputs
|
v
7. Learn Modules
|
v
8. Learn Remote State and Team Workflows
Don't jump directly into complex modules or production infrastructure.
First understand how Terraform creates one resource, tracks it using state, and updates it when the configuration changes.
Common mistakes
Here are six mistakes beginners commonly make while learning Terraform.
Thinking Terraform supports every cloud service automatically: Terraform uses providers, and each provider supports specific resource types and capabilities. Check the Terraform Registry before assuming a service is supported.
Hardcoding AWS credentials in
.tffiles: Never store access keys or secret keys directly in configuration files. Use environment variables, AWS profiles, IAM roles, or other secure authentication methods.Thinking
terraform plancreates infrastructure: Plan only previews the proposed changes.terraform applyperforms the actual operations after confirmation.Deleting the state file manually: Terraform depends on state to identify the resources it manages. Deleting it without a recovery plan can cause Terraform to lose track of existing infrastructure. Back up state and use Terraform state commands for state management.
Committing
terraform.tfstateto GitHub: State files may contain sensitive information. Keep them out of public repositories and use a secured remote backend for shared infrastructure.Using
terraform taintin new workflows: The command is deprecated. Useterraform plan -replaceto preview a resource replacement andterraform apply -replaceto execute it.
Quick recap
Let's quickly revise everything we learned.
Terraform
- Open-source Infrastructure as Code tool.
- Used to provision, update, and destroy infrastructure.
- Supports cloud platforms through providers.
- Uses HCL (HashiCorp Configuration Language).
Providers and resources
- Providers are plugins that communicate with infrastructure platforms.
- Resources represent infrastructure objects managed by Terraform.
Important commands
-
terraform init: Initialize the working directory. -
terraform fmt: Format configuration files. -
terraform validate: Validate configuration. -
terraform plan: Preview infrastructure changes. -
terraform apply: Apply infrastructure changes. -
terraform destroy: Destroy managed infrastructure.
State
-
terraform.tfstatestores information about managed resources. - Local state is stored on your machine.
- Remote state is stored in a shared backend.
- State files can contain sensitive information.
Variables and outputs
- Input variables accept values.
- Output values expose information from resources and modules.
Modules
- Modules are reusable Terraform configurations.
- Root module is the main working directory.
- Child modules are called by other modules.
Resource replacement
-
terraform taintis deprecated. -
terraform untaintremoves a tainted marker. -
terraform apply -replaceis the recommended replacement workflow.
Remember this complete Terraform workflow:
WRITE TERRAFORM CODE
|
v
terraform init
|
v
terraform fmt
|
v
terraform validate
|
v
terraform plan
|
v
terraform apply
|
v
INFRASTRUCTURE CREATED
|
v
terraform destroy
|
v
INFRASTRUCTURE DELETED
Terraform makes infrastructure management programmable, repeatable, and easier to maintain.
Try it yourself
Practice idea:
Create an AWS S3 bucket using Terraform.
Follow these steps:
- Install Terraform.
- Configure AWS authentication.
- Create a
main.tffile. - Declare the AWS provider.
- Create an S3 bucket resource.
- Run
terraform init. - Run
terraform fmtandterraform validate. - Run
terraform plan. - Run
terraform apply. - Verify that the bucket exists in your AWS console.
- Run
terraform destroywhen you no longer need the resource.
Bonus experiment:
Create a reusable S3 bucket module.
Pass the bucket name using an input variable and expose the bucket ARN using an output value.
Then call the same module twice to create two different buckets.
Try changing the bucket configuration and observe how terraform plan identifies the required infrastructure changes.
One final suggestion: experiment with Terraform using a dedicated AWS account or a restricted IAM identity. Always review your plan before applying changes, and clean up resources after testing to avoid unexpected cloud charges.
If this helped, or if you spotted something I should fix, tell me in the comments. I'm still learning too.
Top comments (0)