> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Section Introduction Terraform Workflow

> Overview of the Terraform workflow and best practices for writing configurations, managing state, planning, applying, destroying, and integrating infrastructure as code into CI/CD

Welcome — in this lesson you'll learn the core Terraform workflow for managing cloud infrastructure reliably and repeatably. Terraform (Infrastructure as Code) uses HashiCorp Configuration Language (HCL) to declare desired resource state, then reconciles real infrastructure to match that state. A concise, consistent workflow reduces drift, eases reviews, and enables safe automation with CI/CD.

Core workflow steps (high level)

* Write configuration: define resources and desired state in `.tf` files (HCL).
* Initialize the workspace: download provider plugins and configure the backend.
* Plan changes: generate an execution plan that previews changes.
* Apply changes: execute the plan to change real infrastructure.
* Destroy (optional): remove infrastructure created by Terraform.

Each step exists to make infrastructure changes deliberate and auditable. In practice you should also: manage state (local or remote), use version control for configurations, review plans before applying, and integrate Terraform into CI/CD.

<Callout icon="lightbulb" color="#1CB2FE">
  Always review a `terraform plan` output (or plan file) before running `terraform apply`. Plans are your primary safety check to avoid unintended changes.
</Callout>

Common commands summary

```bash theme={null}
# Initialize the working directory (downloads providers, sets up backend)
terraform init

# Create and show an execution plan (safe preview of changes)
terraform plan

# Apply the planned changes (prompts for approval by default)
terraform apply

# Tear down managed infrastructure
terraform destroy
```

Workflow details, commands, and best practices

* Use version control (Git) for all Terraform code. Treat `.tf` files as the canonical source of truth.
* Prefer remote state backends (e.g., S3 with DynamoDB locking, Terraform Cloud/Enterprise) for team collaboration and state locking.
* Use `terraform plan -out=plan.tfplan` then `terraform apply "plan.tfplan"` to guarantee the apply exactly matches the reviewed plan.
* Protect secrets: avoid committing plaintext secrets. Use environment variables, secret managers, or encrypted variables in CI/CD.

Step-by-step breakdown

1. Write configuration

* Create `.tf` files to declare providers, resources, variables, outputs, and modules.
* Use modules to encapsulate reusable infrastructure patterns.
* Keep environment-specific values out of code; pass them via variables, variable files (`-var-file`), or a workspace-specific backend.
* Example:

```hcl theme={null}
provider "aws" {
  region = var.aws_region
}

resource "aws_s3_bucket" "app_bucket" {
  bucket = var.bucket_name
  acl    = "private"
}
```

2. Initialize the workspace (`terraform init`)

* Downloads provider plugins and modules.
* Configures the backend (local or remote).
* Useful flags:
  * `-backend-config=FILE` to supply backend configuration.
  * `-reconfigure` to ignore existing backend configuration and reinitialize.
* Example:

```bash theme={null}
terraform init -backend-config="bucket=my-terraform-state" -reconfigure
```

3. Plan changes (`terraform plan`)

* Produces an execution plan showing what will be created, changed, or destroyed.
* Common flags:
  * `-out=plan.tfplan` to save the plan for later apply.
  * `-var='key=value'` or `-var-file=prod.tfvars` to inject variables.
  * `-refresh=true|false` to control state refresh.
* Best practice: always run `terraform plan` and review the diff before applying.

4. Apply changes (`terraform apply`)

* Apply can accept a saved plan file or run a fresh plan interactively.
* Typical usage:

```bash theme={null}
# Apply from a previously-saved plan
terraform apply "plan.tfplan"

# or run and apply in one step (prompts for confirmation)
terraform apply

# Non-interactive (CI)
terraform apply -auto-approve
```

* Prefer using saved plan files in automated pipelines to ensure reproducibility.

5. Destroy (`terraform destroy`)

* Safely tear down infrastructure that Terraform manages.
* Use with caution; consider `-target` or manual safeguards if you only want to remove specific resources.

```bash theme={null}
terraform destroy
terraform destroy -target=aws_instance.example
```

State management and locking

* State is critical: it maps your Terraform configuration to real resources.
* Use remote backends for team environments:
  * S3 + DynamoDB (AWS) for state storage + locking
  * Terraform Cloud or Terraform Enterprise for integrated state, locking, runs, and policy
* Encrypt state at rest and limit access.
* Avoid manual edits to state; use `terraform state` subcommands only when necessary.

Workspaces, environments, and branching

* Use separate workspaces (or separate backends/states) per environment (dev, staging, prod).
* Common pattern: separate IaC repos or directories for distinct lifecycles; or use variable files and CI/CD pipelines that target specific backends.
* Prefer distinct state per environment rather than relying on a single workspace to hold multiple unrelated resources.

CI/CD integration

* Create pipelines that:
  1. Run `terraform fmt` and `terraform validate`
  2. Run `terraform plan -out=plan.tfplan` and publish plan output for review
  3. On approval, run `terraform apply plan.tfplan` (non-interactive)
* Store backend secrets and provider credentials in the CI secret store.
* Lock and version provider/plugins by using the `required_providers` block and `terraform lock` file.

Common Commands and Useful Flags

| Command              | Purpose                                                     | Example                                                 |
| -------------------- | ----------------------------------------------------------- | ------------------------------------------------------- |
| `terraform init`     | Initialize directory, download providers, configure backend | `terraform init -backend-config="bucket=team-state"`    |
| `terraform plan`     | Preview changes without applying                            | `terraform plan -out=plan.tfplan -var-file=prod.tfvars` |
| `terraform apply`    | Apply changes to reach desired state                        | `terraform apply "plan.tfplan"`                         |
| `terraform destroy`  | Remove managed infrastructure                               | `terraform destroy -auto-approve`                       |
| `terraform fmt`      | Reformat HCL files                                          | `terraform fmt -recursive`                              |
| `terraform validate` | Validate configuration syntax                               | `terraform validate`                                    |

Security and operations callouts

<Callout icon="warning" color="#FF6B6B">
  Sensitive data can end up in Terraform state. Do not store secrets in plaintext variables that are committed to version control. Use secure secret management and encrypted backends.
</Callout>

Links and references

* Terraform CLI docs: [https://www.terraform.io/cli](https://www.terraform.io/cli)
* Terraform State: [https://www.terraform.io/language/state](https://www.terraform.io/language/state)
* Terraform Backends: [https://www.terraform.io/language/settings/backends](https://www.terraform.io/language/settings/backends)
* Terraform Cloud: [https://www.terraform.io/cloud](https://www.terraform.io/cloud)

Next steps

* We'll next walk through an example repository: initialize a backend, write a small module, run a plan, and apply safely in a CI pipeline. You’ll get hands-on practice with state locking, plan-review workflow, and best practices for team collaboration.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/hashicorp-certified-terraform-associate-004/module/5b03b9b7-5f0f-4df6-8506-7de492c4791d/lesson/a55925df-881f-4ad6-863d-46c9356ce36a" />
</CardGroup>
