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

# Terraform State and Refresh

> Explains Terraform state concepts, inspection and management commands, and how to refresh state to reconcile drift without changing infrastructure.

In this lesson we'll examine Terraform state: what it contains, how to inspect it, and how to refresh it when infrastructure changes outside of Terraform. We previously wrote configuration and applied it — Terraform's true power comes from how it tracks resources in state. Here we'll learn how to view that state, perform safe state maintenance, and reconcile Terraform's view with the actual provider.

## What is Terraform state?

Terraform stores a state file that serves as the authoritative record of resources Terraform manages. This file contains the mapping between resource addresses in your configuration and the actual provider-managed resources (IDs, computed attributes, metadata). Terraform relies on state to plan changes and detect drift.

## Inspecting state

Use the `terraform state` family of commands to inspect and manage the state. To see all tracked resources:

```bash theme={null}
$ terraform state list
azurerm_storage_account.example
```

To view detailed attributes for a single tracked resource:

```bash theme={null}
$ terraform state show azurerm_storage_account.example
# azurerm_storage_account.example:
resource "azurerm_storage_account" "example" {
  access_tier                      = "Hot"
  account_kind                     = "StorageV2"
  account_replication_type         = "LRS"
  account_tier                     = "Standard"
  allow_nested_items_to_be_public  = true
  cross_tenant_replication_enabled = false
  default_to_oauth_authentication  = false
  dns_endpoint_type                = "Standard"
  https_traffic_only_enabled       = true

  id = "/subscriptions/548f7d26-b5b1-468e-ad45-6ee12accf7e7/resourceGroups/my-workshop-eus-rg/providers/Microsoft.Storage/storageAccounts/sadx98rgffe"
}
```

The `state show` output includes both configuration-declared attributes and provider-populated fields (IDs, defaults, and runtime properties). This detailed view is essential for debugging, auditing, and preparing precise state changes.

## State management subcommands

The `terraform state` command exposes subcommands for advanced state maintenance. Terraform automatically creates a timestamped backup of state before any operation that modifies it. Below is a concise reference:

| Subcommand         | Purpose                                                               | Example                                                                                                  |
| ------------------ | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `list`             | List resources recorded in state                                      | `terraform state list`                                                                                   |
| `show`             | Print detailed state for a single resource                            | `terraform state show azurerm_storage_account.example`                                                   |
| `mv`               | Move a resource address within state (useful when refactoring)        | `terraform state mv old.resource new.resource`                                                           |
| `rm`               | Remove instances from state without destroying remote resources       | `terraform state rm module.foo.azurerm_resource.bar`                                                     |
| `replace-provider` | Replace provider references in state (for provider namespace changes) | `terraform state replace-provider registry.terraform.io/old/provider registry.terraform.io/new/provider` |
| `pull`             | Pull the current state and output to stdout (for manual inspection)   | `terraform state pull`                                                                                   |
| `push`             | Update remote state from a local state file (special workflows)       | `terraform state push terraform.tfstate`                                                                 |

The commands are intentionally simple and script-friendly (work well with grep, awk, etc.) for advanced automation and auditing.

<Callout icon="warning" color="#FF6B6B">
  State modification commands can cause drift between Terraform and your real infrastructure if used incorrectly. Always work against a backup and prefer non-destructive commands unless you fully understand the implications.
</Callout>

## Refreshing state

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/ULo-8LXeWHtPzvMr/images/Terraform-On-Azure/Terraform-CLI/Terraform-State-and-Refresh/terraform-refresh-kodekloud-copyright.jpg?fit=max&auto=format&n=ULo-8LXeWHtPzvMr&q=85&s=7026997f47d4ed4708295929c36f2b40" alt="The image contains the text &#x22;Terraform Refresh&#x22; with a copyright notice for KodeKloud at the bottom left." width="1920" height="1080" data-path="images/Terraform-On-Azure/Terraform-CLI/Terraform-State-and-Refresh/terraform-refresh-kodekloud-copyright.jpg" />
</Frame>

Terraform expects the state file to reflect reality. When resources are modified outside Terraform (console edits, manual CLI/API actions, other orchestration tools), the stored state can diverge — this is configuration drift.

Use `terraform refresh` to reconcile Terraform's state with the provider by re-querying resource attributes and updating the state file. Important: `terraform refresh` updates only the state file; it does not change infrastructure.

Example configuration using a variable for the storage account name:

```hcl theme={null}
resource "azurerm_storage_account" "example" {
  name                          = var.storage_account_name
  location                      = "East US"
  resource_group_name           = "my-workshop-eus-rg"
  account_tier                  = "Standard"
  account_replication_type      = "LRS"
  public_network_access_enabled = false
}
```

Running a refresh (supplying the variable):

```bash theme={null}
$ terraform refresh -var "storage_account_name=sadx98rgffe"
azurerm_storage_account.example: Refreshing state...
  [id=/subscriptions/548f7d26-b5b1-468e-ad45-6ee12accf7e7/resourceGroups/my-workshop-eus-rg/providers/Microsoft.Storage/storageAccounts/sadx98rgffe]
```

After running, Terraform has fetched the current resource attributes from Azure and updated the local state to match — no remote changes are made.

<Callout icon="lightbulb" color="#1CB2FE">
  Modern Terraform performs an automatic refresh during operations like `terraform plan` and `terraform apply`, so manually running `terraform refresh` is less common. Still, it's valuable when resolving drift or preparing for direct state edits.
</Callout>

## Key takeaways

* The Terraform state file is the authoritative record of managed infrastructure.
* Inspect state with `terraform state list` and `terraform state show`.
* Use `terraform state` subcommands for advanced maintenance — Terraform creates backups automatically for safety.
* Run `terraform refresh` to update the state from provider data; it updates only the state file and does not alter resources.
* Be cautious with state-modifying commands; test on non-production state or use backups to recover if needed.

## Links and references

* [Terraform State | HashiCorp Documentation](https://www.terraform.io/docs/state/index.html)
* [Terraform CLI Commands](https://www.terraform.io/docs/commands/index.html)
* [Azure Provider for Terraform](https://registry.terraform.io/providers/hashicorp/azurerm/latest)

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/terraform-on-azure/module/a87fc0ec-6ef6-409e-91cb-709bdcebb9eb/lesson/b55fe31e-bb64-4e13-8a58-102864b8b5a5" />
</CardGroup>
