In this guide, you will learn how to list and manipulate Terraform state files using various Terraform state commands. The state file is stored in JSON format, and it is crucial not to edit it manually. Instead, use the provided commands to safely work with your state. Terraform state commands follow this basic syntax: terraform state [subcommand] [options] [address] Each subcommand—such as list, show, move (mv), pull, or rm—is designed to perform a specific operation on the state file.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Listing Resources in the State
Thelist subcommand displays all resource addresses recorded in the Terraform state file. For example, to list all resources:
Showing Resource Details
To inspect detailed attributes of a particular resource, use theshow subcommand. For example, to display all attributes for the S3 bucket resource finance-2020922, run:
Moving Resources in the State
Themove subcommand (or its alias mv) is used to change a resource’s address within the state file. This command is particularly useful when you want to rename a resource without recreating it. It requires specifying both a source address and a destination address.
Consider the following example where you have a DynamoDB table defined in your Terraform configuration and state:
state-locking to state-locking-db without having to recreate it, execute:
terraform apply afterward, Terraform should detect no changes for the renamed resource:
Pulling Remote State
When using remote state, the state file is not saved locally in your configuration directory. Use thepull subcommand to download and print the remote state. For example:
jq for further data manipulation. For instance, to filter and display the hash_key attribute of the state-locking-db table, run:
Removing Resources from the State
Therm (or remove) subcommand deletes one or more resources from the Terraform state file. Removing a resource detaches it from Terraform management without destroying the actual infrastructure. For example, to remove the S3 bucket resource from the state, run:
After removing a resource from the state, remember to also delete or comment out the corresponding resource block in your Terraform configuration file.
That concludes this lesson on Terraform state commands. In the next section, you’ll have the opportunity to work on hands-on labs and practice using these commands in real-world scenarios. For more information about Terraform and managing infrastructure as code, be sure to explore the Terraform Documentation.