Execution
Overview
Terraform provides commands to check, apply, and remove infrastructure safely.
Initialize
Terraform needs to prepare your environment before it can create resources. This is done with terraform init.
- Reads all
.tffiles in your working directory - Downloads required providers automatically
- Detects all modules and writes a list to
.terraform/modules/modules.json - Looks for
terraformblocks withrequired_providersfor third-party providers - Does not verify that your configuration will successfully create resources
To initialize:
terraform init
Expected output:
Initializing the backend...
Initializing provider plugins...
- Finding latest version of hashicorp/aws...
- Installing hashicorp/aws v4.30.0...
Terraform has been successfully initialized!
terraform init happens after you write your configuration but before running terraform plan or terraform apply.
Validate
Checks the configuration files for syntax errors and internal consistency.
terraform validate
Plan
Acts like a dry-run that checks your configuration for errors and dependencies.
- Verifies syntax and variable assignments
- Helps prevent mistakes before applying changes
Command:
terraform plan
Apply
Executes the planned changes and updates the state file.
- Creates or updates resources to match the configuration
- Only modifies resources that need changes
- Writes successful actions to
terraform.state
Command:
terraform apply
Note that this command requires interactive approval before actually making any changes. To bypass the interactive approva:
terraform apply --auto-approve
Destroy
Removes deployed resources in reverse order of creation to respect dependencies defined in the state file.
terraform destroy
Similar with apply, this also requires interactive approval. To bypass it:
terraform destroy --auto-approve
Target Specific Resources
Terraform allows targeting specific resources for testing or debugging.
terraform apply --auto-approve --target=module.webserver
terraform destroy --auto-approve --target=module.webserver
NOTE: This should only be used for debugging, not regular production runs