Bird
Raised Fist0
Terraformcloud~5 mins

State and real infrastructure mapping in Terraform - Commands & Configuration

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
When you use Terraform to create or change cloud resources, it keeps a record called the state. This state helps Terraform know what resources exist and what needs to be updated or deleted. Mapping the state to the real infrastructure means checking that Terraform's record matches what is actually running in the cloud.
When you want to see what resources Terraform has created in your cloud account.
When you need to update or delete resources and want to avoid mistakes.
When you want to check if someone changed resources outside of Terraform.
When you are starting to manage existing resources with Terraform.
When you want to safely plan changes before applying them.
Config File - main.tf
main.tf
terraform {
  required_version = ">= 1.0"
}

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

resource "aws_s3_bucket" "example_bucket" {
  bucket = "example-terraform-bucket-12345"
  acl    = "private"
}

This file tells Terraform to use AWS in the us-east-1 region.

It creates one S3 bucket named "example-terraform-bucket-12345" with private access.

Terraform will track this resource in its state file to map it to the real bucket in AWS.

Commands
This command sets up Terraform in the current folder. It downloads the AWS provider plugin so Terraform can talk to AWS.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/aws... - Installing hashicorp/aws v4.0.0... - Installed hashicorp/aws v4.0.0 (signed by HashiCorp) Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes required for your infrastructure.
This command shows what Terraform will do to match the configuration with the real infrastructure. It compares the state file with the config and cloud resources.
Terminal
terraform plan
Expected OutputExpected
An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # aws_s3_bucket.example_bucket will be created + resource "aws_s3_bucket" "example_bucket" { + acl = "private" + bucket = "example-terraform-bucket-12345" + id = (known after apply) } Plan: 1 to add, 0 to change, 0 to destroy.
This command applies the changes to create the S3 bucket in AWS and updates the state file to map the real resource.
Terminal
terraform apply -auto-approve
Expected OutputExpected
aws_s3_bucket.example_bucket: Creating... aws_s3_bucket.example_bucket: Creation complete after 2s [id=example-terraform-bucket-12345] Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
→
-auto-approve - Automatically approves the apply without asking for confirmation.
This command lists all resources Terraform currently tracks in its state file, showing the mapping to real infrastructure.
Terminal
terraform state list
Expected OutputExpected
aws_s3_bucket.example_bucket
This command shows detailed information about the resources in the state file, confirming what Terraform knows about the real infrastructure.
Terminal
terraform show
Expected OutputExpected
aws_s3_bucket.example_bucket: id = example-terraform-bucket-12345 acl = private bucket = example-terraform-bucket-12345 region = us-east-1
Key Concept

If you remember nothing else from this pattern, remember: Terraform's state file is the trusted record that links your configuration to the real cloud resources.

Common Mistakes
Deleting or changing cloud resources directly in the cloud console without updating Terraform.
Terraform's state will not match the real infrastructure, causing errors or unexpected changes on next apply.
Always make changes through Terraform or update the state using terraform import or terraform state commands.
Losing the state file or not backing it up.
Terraform loses track of resources and cannot safely update or delete them.
Store the state file securely, use remote state storage for teams, and back it up regularly.
Running terraform apply without reviewing terraform plan first.
You might apply unintended changes that affect your real infrastructure.
Always run terraform plan to see proposed changes before applying.
Summary
Use terraform init to prepare your working folder and download necessary plugins.
Use terraform plan to preview changes and see how Terraform maps your config to real resources.
Use terraform apply to create or update resources and update the state file.
Use terraform state list and terraform show to inspect what Terraform tracks and how it maps to real infrastructure.

Practice

(1/5)
1. What is the main purpose of the Terraform state file?
easy
A. To keep track of real infrastructure resources Terraform manages
B. To store user credentials for cloud providers
C. To define the desired infrastructure configuration
D. To log errors during Terraform runs

Solution

  1. Step 1: Understand Terraform state role

    The state file records what resources Terraform has created or manages in the real world.
  2. Step 2: Differentiate state from config and logs

    The configuration defines desired setup, but state tracks actual deployed resources. Credentials and logs are separate concerns.
  3. Final Answer:

    To keep track of real infrastructure resources Terraform manages -> Option A
  4. Quick Check:

    State tracks real resources [OK]
Hint: State file = Terraform's memory of real resources [OK]
Common Mistakes:
  • Confusing state file with configuration files
  • Thinking state stores credentials
  • Assuming state logs errors
2. Which Terraform command shows the current state of resources managed by Terraform?
easy
A. terraform init
B. terraform plan
C. terraform apply
D. terraform state list

Solution

  1. Step 1: Identify command to inspect state

    "terraform state list" displays all resources tracked in the current state file.
  2. Step 2: Differentiate from other commands

    "terraform plan" previews changes, "apply" makes changes, "init" sets up backend and providers.
  3. Final Answer:

    terraform state list -> Option D
  4. Quick Check:

    State inspection command = terraform state list [OK]
Hint: Use 'terraform state list' to see tracked resources [OK]
Common Mistakes:
  • Using 'terraform plan' to check state directly
  • Confusing 'terraform apply' with state inspection
  • Thinking 'terraform init' shows state
3. Given this Terraform state snippet showing one AWS instance resource:
{
  "resources": [
    {
      "type": "aws_instance",
      "name": "web",
      "instances": [
        {"attributes": {"id": "i-1234567890abcdef0", "ami": "ami-0abc1234", "instance_type": "t2.micro"}}
      ]
    }
  ]
}
What is the instance type Terraform currently tracks for this resource?
medium
A. t2.micro
B. ami-0abc1234
C. i-1234567890abcdef0
D. aws_instance

Solution

  1. Step 1: Locate instance_type attribute in state

    The attribute "instance_type" has value "t2.micro" in the resource's attributes.
  2. Step 2: Understand attribute meanings

    "ami" is the image ID, "id" is the instance ID, "type" is resource type, so only "instance_type" matches the question.
  3. Final Answer:

    t2.micro -> Option A
  4. Quick Check:

    Instance type in state = t2.micro [OK]
Hint: Look for 'instance_type' attribute in state JSON [OK]
Common Mistakes:
  • Confusing AMI ID with instance type
  • Picking resource type as instance type
  • Choosing instance ID instead of type
4. You ran terraform apply but your real infrastructure changed outside Terraform. What should you do to fix the state mismatch?
medium
A. Run terraform destroy to remove all resources
B. Run terraform refresh to update the state file with real resource data
C. Manually edit the state file to match real resources
D. Delete the state file and run terraform init again

Solution

  1. Step 1: Understand state drift problem

    When real resources change outside Terraform, state file becomes outdated and causes mismatch.
  2. Step 2: Use terraform refresh to sync state

    "terraform refresh" updates the state file to reflect current real infrastructure without changing resources.
  3. Final Answer:

    Run terraform refresh to update the state file with real resource data -> Option B
  4. Quick Check:

    Sync state with real infra = terraform refresh [OK]
Hint: Use 'terraform refresh' to sync state with real resources [OK]
Common Mistakes:
  • Deleting state file causes loss of tracking
  • Editing state file manually risks corruption
  • Destroying resources is unnecessary for state fix
5. You want to share your Terraform state securely among your team using a remote backend. Which approach best ensures state consistency and safety?
hard
A. Email the state file to team members after each change
B. Store the state file on a shared network drive without locking
C. Use a remote backend like AWS S3 with state locking via DynamoDB
D. Keep the state file local on each developer's machine

Solution

  1. Step 1: Identify remote backend with locking

    A remote backend like AWS S3 combined with DynamoDB locking prevents simultaneous edits and keeps state consistent.
  2. Step 2: Evaluate other options for safety

    Shared drives without locking risk conflicts, emailing state causes version confusion, local files prevent collaboration.
  3. Final Answer:

    Use a remote backend like AWS S3 with state locking via DynamoDB -> Option C
  4. Quick Check:

    Remote backend + locking = safe shared state [OK]
Hint: Use remote backend with locking for team state safety [OK]
Common Mistakes:
  • Ignoring state locking leads to conflicts
  • Sharing state by email causes outdated copies
  • Local state prevents team collaboration