Terraform is an Infrastructure as Code (IaC) tool by HashiCorp that lets you define both cloud and on-prem resources in human-readable configuration files.
Basic Workflow
The standard Terraform workflow consists of four main commands:
terraform init # Initialize the working directory (downloads providers/modules)
terraform plan # Generate and show an execution plan (dry run)
terraform apply # Build or change infrastructure based on the plan
terraform destroy # Destroy all infrastructure managed by TerraformFormatting and Validation
terraform fmt # Reformat your configuration files to standard style
terraform fmt -check # Check if files are formatted correctly (useful for CI/CD)
terraform validate # Check whether the configuration is syntastically validState Management
Terraform uses a state file (terraform.tfstate) to map real-world resources to your configuration.
terraform state list # List all resources currently in the state file
terraform state show <resource> # Show details of a specific resource in the state
terraform state rm <resource> # Remove a resource from the state (does NOT destroy the real resource)
terraform import aws_instance.web i-1234567890 # Import an existing real-world resource into Terraform stateWorkspaces
Workspaces allow you to manage multiple distinct sets of infrastructure (e.g., dev, staging, prod) from the same working directory.
terraform workspace list # List all workspaces
terraform workspace new dev # Create a new workspace named 'dev'
terraform workspace select prod # Switch to the 'prod' workspace
terraform workspace show # Show the name of the current workspaceAuto-Approve and Variables
# Apply without asking for confirmation (Dangerous in production!)
terraform apply -auto-approve
# Pass a variable via command line
terraform apply -var="instance_type=t2.large"
# Use a specific variable file
terraform apply -var-file="production.tfvars"