Terraform.tfstate

Introduction

What is Terraform State?

Terraform state is a tfstate file that records everything Terraform knows about your infrastructure. It maps your configuration to real-world resources and maintains resource metadata.


terraform {
  backend "local" {
    path = "my_state.tfstate"
  }
}

Core Concepts

  • Provider - Plugin for interacting with cloud providers (AWS, GCP, etc.)
  • Resource - A cloud infrastructure component (VM, network, etc.)
  • Resource ID - Unique identifier for cloud resource
  • Depends On - Explicit resource dependencies

State Locking

Prevents concurrent operations on your state file with file-level or backend-level locking. Can be configured with:

Remote state locking:


terraform {
  backend "s3" {
    key = "my-lock-state.tfstate"
  }
}

provider "aws" {
  region = "us-east-1"
}

Getting Started

Installation

Install via your cloud provider's console or using the official CLI:

Configuration

.terraformrc

provider: aws
region: us-west-2
lock_mode: pessimistic
auto_discovery: false

Initialize State File

Terminal
terraform init
Initializing backend..." Initializing provider plugins... Cloud configuration is already set in the CLI configuration file. Terraform has been successfully initialized!

State Management

State Structure

A state file contains these main elements:

Resource Map

  • • Physical name of cloud resource
  • • Current provider information
  • • Attributes

Dependency Graph

  • • Explicit dependencies
  • • Implicit dependencies between resources

State Operations

📥
Import

Add existing resources to your state file
terraform import

🔁
Refresh

Update state with real-world resource status
terraform refresh

🚀
Apply

Implement planned changes
terraform apply

API Reference

State Endpoints

Endpoint Method Description
/api/state GET Get current state file contents
/api/apply POST Process configuration changes
/api/lock PUT Acquire state file lock
/api/versions GET Get version history of state file

Authentication

This API uses API key authentication. Add X-API-Key header with a valid API token.

REQ

Example request with authentication:


curl -X POST "https://terraform.tfstate/api/apply" \
     -H "X-API-Key: your-api-key-here" \
     -H "Content-Type: application/json" \
     -d '{"operation":"destroy","resources":["aws_instance.main"]}'

FAQ

By default, it's stored locally as .terraform/state/terraform.tfstate. You can configure remote backends in your CLI or config file.

Run terraform plan regularly to detect drift. If drift occurs, use terraform refresh to update your state before applying new changes.

While possible, this is strongly discouraged. Use terraform import or terraform apply to make proper state changes.

Use remote state backends like S3, GCS, or Azure Blob Storage to store state files securely. This enables collaboration and avoids merge conflicts.