Sobes.tech
Middle

What is the purpose of the state file?

sobes.tech AI

Answer from AI

The state file in Terraform is used to track the current state of the infrastructure managed by Terraform. It stores a mapping between Terraform configuration elements (resources) and the actual infrastructure resources.

Main purposes of the state file:

  • Mapping configuration to real resources: Allows Terraform to know which elements of the Terraform configuration correspond to existing cloud resources (virtual machines, networks, databases, etc.).
  • Tracking metadata: Stores metadata about resources created by Terraform, such as their IDs, IP addresses, and state.
  • Execution plans (plan): Terraform uses the state file to determine the difference between the desired state (defined in .tf files) and the current infrastructure state. This enables generating a plan of actions that shows what will be changed, created, or destroyed.
  • Locking: When multiple users or CI/CD pipelines work with the same state, the state file can be locked to prevent conflicts and data corruption. Locking mechanisms depend on the backend used (e.g., S3 with DynamoDB).
  • Remote state: In production and team environments, the state file is usually stored in remote storage (S3, Google Cloud Storage, Azure Blob Storage, HashiCorp Consul) instead of locally, providing centralized access and shared use.

Example structure (simplified):

{
  "version": 4,
  "terraform_version": "1.2.3",
  "serial": 1,
  "lineage": "...",
  "outputs": {},
  "resources": [
    {
      "mode": "managed",
      "type": "aws_instance",
      "name": "web_server",
      "provider": "provider[\"registry.terraform.io/hashicorp/aws\"]",
      "instances": [
        {
          "schema_version": 1,
          "attributes": {
            "ami": "ami-...",
            "arn": "arn:aws:ec2:...",
            "id": "i-...",
            "instance_type": "t2.micro",
            // ...other resource attributes
          },
          "sensitive_attributes": [],
          "private": "...",
          "create_before_destroy": false
        }
      ]
    }
    // ...other resources
  ]
}