Skip to main content

Execution

Updated Jan 24, 2021 ·

Overview​

Terraform provides commands to check, apply, and remove infrastructure safely.

Initialize​

Terraform needs to prepare your environment before it can create resources.

  • Reads all .tf files in your working directory
  • Downloads required providers automatically
  • Detects all modules and writes a list to .terraform/modules/modules.json
  • Looks for terraform blocks with required_providers for 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!
info

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.tfstate

Command:

terraform apply

Note that this command requires interactive approval before actually making any changes. To bypass the interactive approval:

terraform apply --auto-approve

Destroy​

Removes deployed resources in reverse order of creation to respect dependencies defined in the state file.

terraform destroy

Similar to 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
warning

Use -target for debugging only. Regular applies should let Terraform evaluate the full dependency graph.