Terraform Basics

Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp. It allows users to define, provision, and manage infrastructure across various cloud providers (like AWS, Azure, and GCP) and on-premises environments using a declarative configuration language known as HCL (HashiCorp Configuration Language).
Terraform is popular because:
It supports multiple cloud providers (AWS, Azure, Google Cloud).
It provides a unified workflow.
It maintains an infrastructure state file to track resources.
It uses a modular approach to manage complex systems.
Key Terraform Commands
Here are the most common terraform commands you will run into:
1. terraform init
Purpose: Prepares the working directory for Terraform operations.
What it does:
Downloads provider plugins.
Initializes the backend for storing the Terraform state.
Verifies the configuration files.
2. terraform validate
Purpose: Checks the configuration files for syntax or logical errors.
What it does:
Ensures that the configuration is syntactically valid.
Validates against the provider's schema but does not connect to the cloud.
3. terraform fmt
Purpose: Formats the configuration files to match the standard style conventions.
What it does:
Ensures consistent indentation and spacing.
Makes code easier to read and maintain.
4. terraform plan
Purpose: Creates an execution plan showing what actions Terraform will take.
What it does:
Highlights the changes required to achieve the desired state.
Outputs actions like resource additions, modifications, or deletions without applying them.
5. terraform apply
Purpose: Executes the actions defined in the execution plan created by
terraform plan.What it does:
Creates, updates, or deletes resources in the infrastructure.
Requires user confirmation before execution unless the
-auto-approveflag is used.
6. terraform plan -destroy
Purpose: Simulates the destruction of resources without actually executing it.
What it does:
Generates a plan detailing which resources will be removed.
Useful for previewing the impact of a
terraform destroycommand.
7. terraform destroy
Purpose: Removes all resources defined in the Terraform configuration.
Note: Always run
terraform plan -destroybefore running anyterraform destroyWhat it does:
Deletes the infrastructure safely and ensures resources are destroyed in the correct order.
You can also target specific resources using the target flag instead of destroying all the resources.
eg.
terraform destroy --target aws_instance.instance_name
8. terraform import
Purpose: Brings existing infrastructure into Terraform's management.
What it does:
Adds resources not originally created with Terraform to the state file.
Does not generate configuration files automatically; you must write the configuration manually.



