terraform/internal/command/state_list.go
Sarah French f5a28cfa8b
Some checks are pending
build / Determine intended Terraform version (push) Waiting to run
build / Determine Go toolchain version (push) Waiting to run
build / Generate release metadata (push) Blocked by required conditions
build / Build for freebsd_386 (push) Blocked by required conditions
build / Build for linux_386 (push) Blocked by required conditions
build / Build for openbsd_386 (push) Blocked by required conditions
build / Build for windows_386 (push) Blocked by required conditions
build / Build for darwin_amd64 (push) Blocked by required conditions
build / Build for freebsd_amd64 (push) Blocked by required conditions
build / Build for linux_amd64 (push) Blocked by required conditions
build / Build for openbsd_amd64 (push) Blocked by required conditions
build / Build for solaris_amd64 (push) Blocked by required conditions
build / Build for windows_amd64 (push) Blocked by required conditions
build / Build for freebsd_arm (push) Blocked by required conditions
build / Build for linux_arm (push) Blocked by required conditions
build / Build for darwin_arm64 (push) Blocked by required conditions
build / Build for linux_arm64 (push) Blocked by required conditions
build / Build for windows_arm64 (push) Blocked by required conditions
build / Build Docker image for linux_386 (push) Blocked by required conditions
build / Build Docker image for linux_amd64 (push) Blocked by required conditions
build / Build Docker image for linux_arm (push) Blocked by required conditions
build / Build Docker image for linux_arm64 (push) Blocked by required conditions
build / Build e2etest for linux_386 (push) Blocked by required conditions
build / Build e2etest for windows_386 (push) Blocked by required conditions
build / Build e2etest for darwin_amd64 (push) Blocked by required conditions
build / Build e2etest for linux_amd64 (push) Blocked by required conditions
build / Build e2etest for windows_amd64 (push) Blocked by required conditions
build / Build e2etest for linux_arm (push) Blocked by required conditions
build / Build e2etest for darwin_arm64 (push) Blocked by required conditions
build / Build e2etest for linux_arm64 (push) Blocked by required conditions
build / Run e2e test for linux_386 (push) Blocked by required conditions
build / Run e2e test for windows_386 (push) Blocked by required conditions
build / Run e2e test for darwin_amd64 (push) Blocked by required conditions
build / Run e2e test for linux_amd64 (push) Blocked by required conditions
build / Run e2e test for windows_amd64 (push) Blocked by required conditions
build / Run e2e test for linux_arm (push) Blocked by required conditions
build / Run e2e test for linux_arm64 (push) Blocked by required conditions
build / Run terraform-exec test for linux amd64 (push) Blocked by required conditions
Quick Checks / Unit Tests (push) Waiting to run
Quick Checks / Race Tests (push) Waiting to run
Quick Checks / End-to-end Tests (push) Waiting to run
Quick Checks / Code Consistency Checks (push) Waiting to run
PSS: Update how commands access backends, so both backend and state_store configuration can be used (#37569)
* Add a generic method for loading an operations backend in non-init commands

* Refactor commands to use new prepareBackend method: group 1

* Refactor commands to use new prepareBackend method: group 2, where config parsing needs to be explicitly added

* Refactor commands to use new prepareBackend method: group 3, where we can use already parsed config

* Additional, more nested, places where logic for accessing backends needs to be refactored

* Remove duplicated comment

* Add test coverage of `(m *Meta) prepareBackend()`

* Add TODO related to using plans for backend/state_store config in apply commands

* Add `testStateStoreMockWithChunkNegotiation` test helper

* Add assertions to tests about the backend (remote-state, local, etc) in use within operations backend

* Stop prepareBackend taking locks as argument

* Code comment in prepareBackend

* Replace c.Meta.prepareBackend with c.prepareBackend

* Change `c.Meta.loadSingleModule` to `c.loadSingleModule`

* Rename (Meta).prepareBackend to  (Meta).backend, update godoc comment to make relationship to (Meta).Backend more obvious.

* Revert change from config.Module to config.Root.Module

* Update `(m *Meta) backend` method to parse config itself, and also to adhere to calling code's viewtype instructions

* Update all tests and calling code following previous commit

* Change how an operations backend is obtained by autocomplete code

* Update autocomplete to return nil if no workspace names are returned from the backend

* Add test coverage for autocompleting workspace names when using a pluggable state store

* Fix output command: pass view type data to new `backend` method

* Fix in plan command: pass correct view type to `backend` method

* Fix `providers schema` command to use correct viewtype when preparing a backend
2025-11-03 17:57:20 +00:00

144 lines
3.9 KiB
Go

// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package command
import (
"fmt"
"strings"
"github.com/hashicorp/cli"
"github.com/hashicorp/terraform/internal/addrs"
"github.com/hashicorp/terraform/internal/command/arguments"
"github.com/hashicorp/terraform/internal/states"
)
// StateListCommand is a Command implementation that lists the resources
// within a state file.
type StateListCommand struct {
Meta
StateMeta
}
func (c *StateListCommand) Run(args []string) int {
args = c.Meta.process(args)
var statePath string
cmdFlags := c.Meta.defaultFlagSet("state list")
cmdFlags.StringVar(&statePath, "state", "", "path")
lookupId := cmdFlags.String("id", "", "Restrict output to paths with a resource having the specified ID.")
if err := cmdFlags.Parse(args); err != nil {
c.Ui.Error(fmt.Sprintf("Error parsing command-line flags: %s\n", err.Error()))
return cli.RunResultHelp
}
args = cmdFlags.Args()
if statePath != "" {
c.Meta.statePath = statePath
}
// Load the backend
b, diags := c.backend(".", arguments.ViewHuman)
if diags.HasErrors() {
c.showDiagnostics(diags)
return 1
}
// This is a read-only command
c.ignoreRemoteVersionConflict(b)
// Get the state
env, err := c.Workspace()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error selecting workspace: %s", err))
return 1
}
stateMgr, sDiags := b.StateMgr(env)
if sDiags.HasErrors() {
c.Ui.Error(fmt.Sprintf(errStateLoadingState, sDiags.Err()))
return 1
}
if err := stateMgr.RefreshState(); err != nil {
c.Ui.Error(fmt.Sprintf("Failed to load state: %s", err))
return 1
}
state := stateMgr.State()
if state == nil {
c.Ui.Error(errStateNotFound)
return 1
}
var addrs []addrs.AbsResourceInstance
if len(args) == 0 {
addrs, diags = c.lookupAllResourceInstanceAddrs(state)
} else {
addrs, diags = c.lookupResourceInstanceAddrs(state, args...)
}
if diags.HasErrors() {
c.showDiagnostics(diags)
return 1
}
for _, addr := range addrs {
if is := state.ResourceInstance(addr); is != nil {
if *lookupId == "" || *lookupId == states.LegacyInstanceObjectID(is.Current) {
c.Ui.Output(addr.String())
}
}
}
c.showDiagnostics(diags)
return 0
}
func (c *StateListCommand) Help() string {
helpText := `
Usage: terraform [global options] state list [options] [address...]
List resources in the Terraform state.
This command lists resource instances in the Terraform state. The address
argument can be used to filter the instances by resource or module. If
no pattern is given, all resource instances are listed.
The addresses must either be module addresses or absolute resource
addresses, such as:
aws_instance.example
module.example
module.example.module.child
module.example.aws_instance.example
An error will be returned if any of the resources or modules given as
filter addresses do not exist in the state.
Options:
-state=statefile Path to a Terraform state file to use to look
up Terraform-managed resources. By default, Terraform
will consult the state of the currently-selected
workspace.
-id=ID Filters the results to include only instances whose
resource types have an attribute named "id" whose value
equals the given id string.
`
return strings.TrimSpace(helpText)
}
func (c *StateListCommand) Synopsis() string {
return "List resources in the state"
}
const errStateLoadingState = `Error loading the state: %[1]s
Please ensure that your Terraform state exists and that you've
configured it properly. You can use the "-state" flag to point
Terraform at another state file.`
const errStateNotFound = `No state file was found!
State management commands require a state file. Run this command
in a directory where Terraform has been run or use the -state flag
to point the command to a specific state location.`