Skip to main content

Command Palette

Search for a command to run...

TerraWeek day 4:

Published
•7 min read
TerraWeek day 4:
A

Passionate AWS Developer | DevOps Engineer with a strong background in cloud architecture and solutions engineering. Leveraging the power of Amazon Web Services (AWS), knowledge of the AWS global infrastructure, design and implement robust cloud-based solutions that align with clients' specific needs.

Task 01:

Importance of Terraform State-

📚 Research: Dive into the importance of Terraform state in managing infrastructure. Discover how Terraform state helps track the current state of resources and ensures smooth infrastructure provisioning and management.

Terraform state is a critical component of Terraform, a popular infrastructure-as-code (IAC) tool used for provisioning and managing infrastructure resources in a declarative manner.

Terraform state is a fundamental and vital aspect of using Terraform for infrastructure management. It ensures that your infrastructure is correctly managed, dependencies are resolved, and changes are tracked accurately, making it a reliable and robust IAC tool for building and maintaining infrastructure.

It keeps the records of all the resources that have been created.

The importance of Terraform state can be summarized as follows:

  1. Tracking Resource State: Terraform state stores the current state of your infrastructure. This is essential for Terraform to understand what resources have been created and their current configuration. Without this information, Terraform would not know how to manage or modify your infrastructure.

  2. Dependency Resolution: Terraform uses the state to establish dependencies between resources. It determines the order in which resources should be created, updated, or destroyed to ensure that everything is managed correctly and that dependencies are resolved in the right order.

  3. Change Detection: When you make changes to your Terraform configuration (e.g., altering resource properties or adding new resources), Terraform compares the desired state (your configuration) with the current state stored in the state file. This allows Terraform to detect what needs to be created, updated, or destroyed.

  4. Resource Locking: Terraform state provides a locking mechanism to prevent multiple users or automation processes from simultaneously modifying the same infrastructure. This ensures that only one operation is modifying the state at a time, which is crucial for preventing conflicts.

  5. Collaboration: When working in a team or collaborating on infrastructure, sharing a Terraform state file allows team members to have a consistent view of the infrastructure. It ensures that everyone is working with the same set of resources and their current configuration.

  6. Remote State Management: Storing the state remotely, such as in an S3 bucket or a remote key-value store, is a best practice. This makes it easier to collaborate, and it provides version control and better security than keeping state files on local machines.

  7. Secure Sensitive Information: State files may contain sensitive information, so managing them securely is crucial. Remote state management allows for encrypting sensitive data, which enhances security.

  8. State Recovery: In the event of a disaster or the loss of your local state, a remote state enables you to recover your infrastructure and continue managing it without losing progress.

Terraform Workspaces: State is used in Terraform workspaces to maintain different copies of your infrastructure for various environments (e.g., development, staging, production) or different configurations.

Task 2:

Local State and terraform state Command

Local State in Terraform refers to the default method of storing the state of your infrastructure that Terraform manages and the terraform state command is a tool used to interact with this state. The state information contains details about the resources Terraform is managing, their current attributes, dependencies, and other essential data to ensure that Terraform can make informed decisions about how to create, modify, or destroy resources.

  1. Local State:

    Local state is the default method of storing Terraform's state information. When you run terraform apply or terraform init, Terraform stores the state in a local file named terraform.tfstate by default. This file is usually stored in the same directory as your Terraform configuration files. Local state is straightforward to set up and use for small, single-user projects. However, it has some limitations:

    • It's not suitable for team collaboration because it's stored on an individual's machine, making it difficult to share and maintain state across multiple team members.

    • It doesn't provide strong data security, as the state file may contain sensitive information.

    • There's no inherent version control, so you might accidentally overwrite or lose state data.

  2. terraform state Command:

    The terraform state command is a tool that allows you to interact with the state data stored in your local or remote state files. It's useful for inspecting, modifying, or fixing the state information.

    Here are some common subcommands of terraform state:

    • terraform state show <resource>: This command allows you to view the details of a specific resource's state. For example, you can use terraform state show aws_instance.example to inspect the state of an EC2 instance named "example."

    • terraform state list: Use this command to list all the resources managed by Terraform in your current state file. This provides an overview of the resources currently tracked by Terraform.

    • terraform state rm <resource>: This command is used to remove a resource from the state. It's typically used when a resource was manually destroyed (e.g., outside of Terraform) and needs to be removed from the state file.

    • terraform state replace-provider: This is used to replace the provider for a resource in the state when you want to migrate resources to a different provider.

  3. Remote State:

    It's recommended to use remote state management for team collaboration and more complex projects. Remote state solutions like Amazon S3, Azure Blob Storage, HashiCorp Consul, or HashiCorp Terraform Cloud offer improved security, collaboration, and versioning capabilities compared to local state. They also help prevent accidental state corruption or loss.

Task 03:

Remote State Management:

📚 Explore*: Delve into remote state management options like Terraform Cloud, AWS S3, Azure Storage Account, or HashiCorp Consul. Select one remote state management option and thoroughly research its setup and configuration process. Become familiar with the steps required to leverage remote state management in your Terraform workflow.*

Remote state management is a crucial aspect of using Terraform, especially in collaborative and production environments. There are several remote state backends to choose from, such as Terraform Cloud, AWS S3, Azure Storage Account, and HashiCorp Consul. In this response, I'll explore the setup and configuration process for using AWS S3 as a remote state backend for Terraform.

AWS S3 Remote State Backend for Terraform and AWS DynamoDb to enable state locking to prevent concurrent access:

  • Create a new repository mkdir terraform-remote

  • Write the following configuration file backend-infra.tf and save it.

      terraform {
              required_providers {
                      aws = {
                      source = "hashicorp/aws"
                      version = "5.16.1"
                      }
          }
      }
      provider "aws" {
              region = "us-east-1"
      }
      resource "aws_s3_bucket" "backend-buket" {
              bucket = "buckk-bnd"
      }
    
      resource "aws_dynamodb_table" "dynamodb-table" {
              name = "back-table"
              billing_mode = "PAY_PER_REQUEST"
              hash_key = "LockID"
              attribute {
                      name = "LockID"
                      type = "S"
                  }
      }
    
  • Initialize the Terraform repo by executing terraform init.

  • Run the command terraform plan and terraform apply to apply the configuration and then the S3 bucket and dynamodb table will be created for the remote backend.

Using AWS S3 as a remote state backend and dynamoDb for the state locking provides the advantages of versioning, security, and scalability, and it's a recommended practice when working with Terraform in a collaborative setting.

Task 04:

Modify: Enhance your Terraform configuration file to store the state remotely using the chosen remote state management option. Include the necessary backend configuration block in your Terraform configuration file to enable seamless remote state storage and access.

Got to terraform.tf file and add the backend block in file.

Here is the configuration for the remote state. we have added the S3 bucket and configured the backed block, so it can store state files remotely.

terraform {
        required_providers {
                aws = {
                source = "hashicorp/aws"
                version = "5.16.1"
                }
        }


backend "s3" {
        bucket = "buckk-bnd"
        dynamodb_table = "back-table"
        region = "us-east-1"
        key = "terraform.tfstate"
        }
}

Initialize the Terraform repo by executing terraform init.

Run the command terraform plan and terraform apply to apply the configuration and then the S3 bucket and dynamodb table will be created for the remote backend.

By following these steps, you've enhanced your Terraform configuration to store the state remotely using AWS S3 as the remote state management option. This setup offers the benefits of remote state management, such as better collaboration, state versioning, and improved security for your infrastructure code.

More from this blog

Akarsha's blog

28 posts