DEV Community

Stephanie Makori
Stephanie Makori

Posted on

Using Terraform Locals and Remote State in Practice

Day 6 focused on improving code readability and understanding how Terraform manages infrastructure behind the scenes.

Using Locals for Cleaner Code

I introduced the locals block to remove repeated values and simplify naming across my configuration.

locals {
team = "api_mgmt_dev"
application = "corp_api"
server_name = "ec2-${var.environment}-api-${var.variables_sub_az}"
}

Instead of hardcoding tags, I used:

tags = {
Name = local.server_name
Owner = local.team
App = local.application
}

This made the code easier to maintain and more consistent.

Understanding Terraform State

Terraform stores infrastructure details in a file called terraform.tfstate. This file tracks resource IDs, attributes, and relationships between resources.

I verified this by running:

terraform state list

and:

terraform state show aws_instance.web_server

This showed detailed information such as the instance ID, public IP, and applied tags.

Moving to Remote State

I configured remote state using S3 and enabled locking with DynamoDB.

After adding the backend configuration, I ran:

terraform init

Terraform detected the existing local state and prompted me to migrate it to the S3 backend. After approving the migration, Terraform successfully moved the state and confirmed that the infrastructure matched the configuration.

Running terraform apply after migration showed no changes, which confirmed that the remote state was consistent with the deployed resources.

Testing State Locking

To test locking, I ran terraform apply in one terminal and terraform plan in another.

The second command failed with:

Error acquiring the state lock
ConditionalCheckFailedException

This confirmed that Terraform was using DynamoDB to prevent multiple operations from modifying the state at the same time.

Key Takeaways

  • Locals improve readability and reduce duplication
  • Terraform state tracks the real infrastructure
  • Remote state enables collaboration
  • State locking prevents conflicts

Final Thoughts

This day showed that Terraform is not just about creating resources. It is also about managing infrastructure safely and consistently over time.

Understanding state and locking is essential for working in real world environments.

Terraform #AWS #DevOps #InfrastructureAsCode #CloudComputing

Top comments (0)