Terraform Workflow

terraform-learning Hands-on Terraform configs, modules, and practice projects on GitHub.

Terraform Workflow

The common Terraform workflow is:

Write Configuration
        │
        ▼
terraform init
        │
        ▼
terraform fmt
        │
        ▼
terraform validate
        │
        ▼
terraform plan
        │
        ▼
terraform apply

And when infrastructure is no longer needed:

terraform destroy

1. terraform init

Initializes the Terraform project.

terraform init

It mainly:

  • Downloads required providers
  • Initializes the backend
  • Downloads modules

For example, if we use:

provider "aws" {
  region = "ap-south-1"
}

terraform init downloads the required AWS provider.

Usually run it when:

New Terraform project
        ↓
terraform init

Or after changing providers, modules, or backend configuration.


2. terraform fmt

Formats Terraform files into the standard Terraform style.

terraform fmt

For example:

resource "aws_instance" "backend" {
ami="ami-123456"
instance_type="t3.micro"
}

Becomes:

resource "aws_instance" "backend" {
  ami           = "ami-123456"
  instance_type = "t3.micro"
}

Think:

terraform fmt
      ↓
Format Terraform code

3. terraform validate

Checks whether the Terraform configuration is syntactically and internally valid.

terraform validate

Successful result:

Success! The configuration is valid.

Think:

terraform validate
        ↓
"Is my Terraform configuration valid?"

4. terraform plan

Shows what Terraform plans to change before actually changing infrastructure.

terraform plan

Terraform may show:

+ create
~ update
- destroy

Example:

+ aws_instance.backend

means Terraform plans to create the resource.

The important idea:

Terraform Code
      │
      ▼
terraform plan
      │
      ▼
Preview Changes
      │
      ├── Create
      ├── Update
      └── Destroy

Always review the plan before applying important infrastructure changes.


5. terraform apply

Applies the changes and creates/updates/deletes the actual infrastructure.

terraform apply

Terraform first shows the plan and asks:

Do you want to perform these actions?

Enter a value:

Enter:

yes

Then Terraform performs the changes.

Flow:

Terraform Configuration
        │
        ▼
terraform apply
        │
        ▼
AWS / Cloud Provider
        │
        ▼
Infrastructure Created
        │
        ▼
State Updated

6. terraform destroy

Destroys infrastructure managed by the current Terraform configuration/state.

terraform destroy

Flow:

Terraform State
      │
      ▼
terraform destroy
      │
      ▼
Managed Resources
      │
      ▼
Destroyed

Be careful with this command, especially in production.


Common Practical Workflow

While developing:

terraform fmt

terraform validate

terraform plan

terraform apply

For a brand-new project:

terraform init

terraform fmt

terraform validate

terraform plan

terraform apply

When finished with practice infrastructure:

terraform destroy