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

> Explains Terraform state management, its contents, local versus remote backends, security and collaboration considerations, and using remote storage for team workflows.

Now that we understand what Terraform state is, let’s examine how Terraform manages state in practice and why it matters for collaboration, safety, and incremental updates.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/ULo-8LXeWHtPzvMr/images/Terraform-On-Azure/Terraform-State-Fundamentals/Terraform-State-Management/terraform-state-management-minimalist-design.jpg?fit=max&auto=format&n=ULo-8LXeWHtPzvMr&q=85&s=d053699af922245a1a7a7011c4ed7ab6" alt="The image features the text &#x22;Terraform State Management&#x22; with a minimalist design, including a gradient blue shape on a white background." width="1920" height="1080" data-path="images/Terraform-On-Azure/Terraform-State-Fundamentals/Terraform-State-Management/terraform-state-management-minimalist-design.jpg" />
</Frame>

## Example: A simple Azure Storage Account

Here is a minimal `azurerm_storage_account` resource using a `variable` for the storage account name:

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

variable "storage_account_name" {
  type        = string
  description = "Name of the Azure Storage Account"
}
```

When you run `terraform apply` and pass the storage account name, Terraform does two things:

* Creates (or updates) the resource in Azure.
* Writes a local state file called `terraform.tfstate` (by default).

You do not create this file manually—Terraform manages it automatically.

Example apply and local state output:

```bash theme={null}
$ terraform apply -var "storage_account_name=sfx097674"

# After apply, listing the directory shows terraform.tfstate
$ ls -lah
total 56
drwxr-xr-x  8 rithinskarla staff 256B May 13 06:31  .
drwxr-xr-x  8 rithinskarla staff 256B May 12 19:50  ..
drwxr-xr-x  3 rithinskarla staff 96B May 12 16:27  .terraform
-rw-r--r--  1 rithinskarla staff 1.1K May 12 16:27  .terraform.lock.hcl
-rw-r--r--  1 rithinskarla staff 415B May 13 06:28  main.tf
-rw-r--r--  1 rithinskarla staff 159B May 12 16:27  providers.tf
-rw-r--r--  1 rithinskarla staff 8.4K May 13 06:31  terraform.tfstate
-rw-r--r--  1 rithinskarla staff 861B May 12 16:27  variables.tf
```

This `terraform.tfstate` file represents the current infrastructure as Terraform knows it.

## What is inside the state file?

Terraform state acts as the authoritative mapping between your configuration and the real-world infrastructure. Think of it as Terraform’s memory: without it, Terraform cannot determine which resources exist, their IDs, or which attributes have changed.

A simplified excerpt of a Terraform state file (JSON):

```json theme={null}
{
  "version": 4,
  "terraform_version": "1.5.7",
  "serial": 1,
  "lineage": "62f9521-2fc2-a699-211f-e1f306c99896",
  "outputs": {},
  "resources": [
    {
      "mode": "managed",
      "type": "azurerm_storage_account",
      "name": "example",
      "provider": "provider[\"registry.terraform.io/hashicorp/azurerm\"]",
      "instances": [
        {
          "schema_version": 4,
          "attributes": {
            "access_tier": "Hot",
            "account_kind": "StorageV2",
            "account_replication_type": "LRS",
            "account_tier": "Standard",
            "allow_nested_items_to_be_public": true,
            "allowed_copy_scope": "",
            "azure_files_authentication": [],
            "blob_properties": []
          }
        }
      ]
    }
  ]
}
```

This JSON includes provider info, resource types and names, and all recorded attributes (SKU, replication type, access tier, etc.). Because the state can contain sensitive or critical information (resource IDs, endpoints, sometimes secrets), protecting state is essential.

<Callout icon="lightbulb" color="#1CB2FE">
  Protect your state: state files can contain sensitive values (resource IDs, endpoints, and occasionally secrets). When storing state remotely, enable encryption and strict access controls to prevent unauthorized access.
</Callout>

## Where is state stored?

* By default: `terraform.tfstate` stored locally in your working directory. This is fine for learning, demos, or single-user scenarios.
* For teams and automation: use a remote backend (Azure Storage, Amazon S3, Terraform Cloud, etc.) to centralize state, provide locking, and improve access control.

<Callout icon="warning" color="#FF6B6B">
  Warning: Local state lacks concurrency protection. Multiple users or CI jobs operating on the same local state can cause conflicts or corruption. Use a remote backend for team workflows.
</Callout>

## Remote backends — why and when to use them

Remote backends provide several advantages:

* Centralized storage so all team members and CI pipelines use the same state.
* Locking support (depending on backend) to prevent concurrent operations.
* Access control, auditability, and encryption at rest.
* Integration with remote runs and workspace concepts (e.g., Terraform Cloud).

Popular backend options:

* Azure Storage Account: reliable for Azure-native workflows.
* Amazon S3 (with DynamoDB locking): common for AWS and cross-cloud setups.
* Terraform Cloud: managed state, remote runs, and policy enforcement.

References:

* [Azure Storage Account overview](https://learn.microsoft.com/azure/storage/common/storage-account-overview)
* [Amazon S3](https://aws.amazon.com/s3/)
* [Terraform Cloud](https://www.terraform.io/cloud)

## Quick comparison: local vs remote state

| Aspect                 | Local state (`terraform.tfstate`) | Remote backend                     |
| ---------------------- | --------------------------------: | ---------------------------------- |
| Best for               |      Single user, experimentation | Teams, CI/CD, production           |
| Concurrency protection |                                No | Usually yes (depending on backend) |
| Access control         |          OS/file permissions only | Fine-grained RBAC, cloud IAM       |
| Encryption at rest     |                            Manual | Typically provided by backend      |
| Recovery / backups     |                  Manual snapshots | Backend-managed/versioned          |

## Why state matters (summary)

* Maps Terraform configuration to real resources (IDs, attributes).
* Enables incremental updates — Terraform only modifies what changed.
* Prevents duplicate resource creation and is required for plan/apply/destroy/import.
* Serves as the source of truth for Terraform operations.

Check your working directory for `terraform.tfstate` to confirm the resources you’ve deployed.

Now that you understand Terraform state and why it’s important, the next step is to configure a remote backend suited to your team and automation needs.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/terraform-on-azure/module/d0fef6dd-c271-403d-b4ac-ee1f20c1839b/lesson/130cadb8-31f6-42e0-8ef0-4686ad423a81" />
</CardGroup>
