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

# Introduction to the Terraform CLI

> Overview of Terraform CLI command structure, workflow, common subcommands, environment variables, and best practices for managing infrastructure as code

The Terraform CLI is the primary interface for managing infrastructure as code with Terraform. It provides a consistent command structure across cloud providers and on-premises environments, so the same commands and workflow apply whether you're deploying to AWS, Azure, GCP, or elsewhere. This predictability helps teams collaborate and automate infrastructure reliably.

A typical command pattern is:

```bash theme={null}
terraform <command> [options]
```

Once you learn the CLI conventions, you can apply them across every Terraform project.

## Command structure and examples

Commands are invoked with the base keyword `terraform` followed by a subcommand and optional flags or parameters:

```bash theme={null}
terraform <subcommand> [options or flags]
```

Example:

```bash theme={null}
terraform plan -out=planfile
```

* `terraform` — invokes the Terraform CLI.
* `plan` — subcommand that generates an execution plan.
* `-out=planfile` — optional flag that saves the plan for later use with `apply`.

Use this structure to compose commands for initialization, validation, planning, applying, and destruction.

## Terraform workflow mapped to CLI commands

Terraform’s recommended workflow maps directly to CLI subcommands. Follow these steps to develop, test, and manage infrastructure safely.

| Step              | Purpose                                                                  | CLI Examples                                         |
| ----------------- | ------------------------------------------------------------------------ | ---------------------------------------------------- |
| Write             | Create infrastructure definitions in HCL (`.tf` files).                  | `# Edit .tf files`                                   |
| Format & Validate | Ensure readable, valid configuration.                                    | `terraform fmt`<br />`terraform validate`            |
| Init              | Initialize the working directory: download providers, configure backend. | `terraform init`                                     |
| Plan              | Preview proposed changes before applying.                                | `terraform plan`<br />`terraform plan -out=planfile` |
| Apply             | Provision or modify resources described in configuration.                | `terraform apply`<br />`terraform apply planfile`    |
| Destroy           | Tear down managed resources.                                             | `terraform destroy`                                  |

Canonical sequence of commands:

```bash theme={null}
terraform fmt
terraform init
terraform validate
terraform plan
terraform apply
# terraform destroy
```

Note: Running `terraform plan` before `terraform apply` is a best practice—it lets you review changes and avoids surprises.

<Callout icon="warning" color="#FF6B6B">
  Be careful with `terraform destroy`. It will remove infrastructure managed by Terraform. Confirm that you really intend to destroy resources before typing `yes`.
</Callout>

## Core CLI commands — quick reference

Below are the most commonly used Terraform subcommands with a short description and example usage.

| Command              | Purpose                                                     | Example                                            |
| -------------------- | ----------------------------------------------------------- | -------------------------------------------------- |
| `terraform init`     | Initialize a working directory and download providers.      | `terraform init`                                   |
| `terraform fmt`      | Format configuration files.                                 | `terraform fmt`                                    |
| `terraform validate` | Validate configuration for syntax and internal consistency. | `terraform validate`                               |
| `terraform plan`     | Generate and display an execution plan.                     | `terraform plan -out=planfile`                     |
| `terraform apply`    | Execute changes to reach the desired state.                 | `terraform apply`                                  |
| `terraform destroy`  | Destroy remote resources managed by a configuration.        | `terraform destroy`                                |
| `terraform state`    | Inspect and modify the state file.                          | `terraform state list`                             |
| `terraform show`     | Show state or saved plan details.                           | `terraform show planfile`                          |
| `terraform import`   | Import existing resources into state.                       | `terraform import aws_instance.example i-12345678` |

This list is not exhaustive but covers the commands most teams use daily.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/urHSIc4JjzJnqdR4/images/HashiCorp-Certified-Terraform-Associate-004/Terraform-CLI/Introduction-to-the-Terraform-CLI/terraform-subcommands-checked-list.jpg?fit=max&auto=format&n=urHSIc4JjzJnqdR4&q=85&s=d41650025119d8f021a13af153d633ea" alt="The image lists various Terraform subcommands, with some checked off, such as &#x22;apply,&#x22; &#x22;init,&#x22; &#x22;destroy,&#x22; &#x22;validate,&#x22; and &#x22;version.&#x22; It also notes that this is not an exhaustive list." width="1920" height="1080" data-path="images/HashiCorp-Certified-Terraform-Associate-004/Terraform-CLI/Introduction-to-the-Terraform-CLI/terraform-subcommands-checked-list.jpg" />
</Frame>

## Additional commonly used subcommands

Beyond the core workflow, Terraform includes powerful subcommands for state management, debugging, and advanced operations:

* `terraform state` — inspect and manually modify state objects (use carefully).
* `terraform show` — display state or plan details in a human-readable format.
* `terraform import` — bring existing external resources under Terraform management.
* `terraform fmt` and `terraform validate` — help enforce configuration quality and consistency.

## Environment variables

Environment variables are a secure, convenient way to provide credentials, configure Terraform behavior, and set input variables without embedding secrets in `.tf` files.

Why use environment variables?

* Avoid committing credentials into version control.
* Provide defaults or overrides for variables in CI/CD pipelines.
* Control logging and runtime behavior for debugging.

Common environment variables:

* `TF_LOG` — set Terraform logging level (`TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`). Useful for troubleshooting.
* `TF_VAR_<name>` — set Terraform input variables from the environment. For example:
  ```bash theme={null}
  export TF_VAR_server_name="prod-db-01"
  ```
  A configuration referencing `var.server_name` will pick up this value.
* Provider-specific variables — many providers support environment-based credentials (for example AWS or Azure environment variables). Terraform checks multiple sources for credentials, including environment variables and credential helpers.

Example combined environment setup:

```bash theme={null}
export TF_LOG=DEBUG
export TF_VAR_server_name="prod-db-01"
export AWS_ACCESS_KEY_ID="EXAMPLEACCESSKEY"
export AWS_SECRET_ACCESS_KEY="EXAMPLESECRETKEY"
```

<Callout icon="lightbulb" color="#1CB2FE">
  Use environment variables for credentials and sensitive values instead of hardcoding them into `.tf` files to reduce the risk of accidentally committing secrets.
</Callout>

## Best practices and tips

* Always run `terraform fmt` and `terraform validate` before committing changes.
* Use `terraform plan -out=planfile` and `terraform apply planfile` to ensure the exact planned changes are applied.
* Store state securely (remote backends like S3 with locking via DynamoDB, or HashiCorp Consul, are recommended for team workflows).
* Use workspaces, modules, and variable files to organize environments and reusable components.
* Limit the use of `terraform state` commands; prefer importing and re-creating resources through configuration when possible.

## Links and references

* Terraform documentation: [https://www.terraform.io/docs](https://www.terraform.io/docs)
* Terraform CLI reference: [https://www.terraform.io/cli](https://www.terraform.io/cli)
* State and backends: [https://www.terraform.io/language/state](https://www.terraform.io/language/state)

Wrapping up

You now have a concise, practical overview of the Terraform CLI: its command structure, mapped workflow, useful subcommands, and secure use of environment variables. In later sections you can explore advanced topics like remote state backends, workspaces, custom providers, and automation patterns for CI/CD.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/hashicorp-certified-terraform-associate-004/module/35cbc795-57ed-4af7-88c8-c9323af9294d/lesson/b6d18b73-a1cc-4a58-b6d7-90cf07a6dd27" />
</CardGroup>
