github.com/iaas-resource-provision/iaas-rpc@v1.0.7-0.20211021023331-ed21f798c408/internal/command/state_list.go (about)

     1  package command
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/iaas-resource-provision/iaas-rpc/internal/addrs"
     8  	"github.com/iaas-resource-provision/iaas-rpc/internal/states"
     9  	"github.com/iaas-resource-provision/iaas-rpc/internal/tfdiags"
    10  	"github.com/mitchellh/cli"
    11  )
    12  
    13  // StateListCommand is a Command implementation that lists the resources
    14  // within a state file.
    15  type StateListCommand struct {
    16  	Meta
    17  	StateMeta
    18  }
    19  
    20  func (c *StateListCommand) Run(args []string) int {
    21  	args = c.Meta.process(args)
    22  	var statePath string
    23  	cmdFlags := c.Meta.defaultFlagSet("state list")
    24  	cmdFlags.StringVar(&statePath, "state", "", "path")
    25  	lookupId := cmdFlags.String("id", "", "Restrict output to paths with a resource having the specified ID.")
    26  	if err := cmdFlags.Parse(args); err != nil {
    27  		c.Ui.Error(fmt.Sprintf("Error parsing command-line flags: %s\n", err.Error()))
    28  		return cli.RunResultHelp
    29  	}
    30  	args = cmdFlags.Args()
    31  
    32  	if statePath != "" {
    33  		c.Meta.statePath = statePath
    34  	}
    35  
    36  	// Load the backend
    37  	b, backendDiags := c.Backend(nil)
    38  	if backendDiags.HasErrors() {
    39  		c.showDiagnostics(backendDiags)
    40  		return 1
    41  	}
    42  
    43  	// This is a read-only command
    44  	c.ignoreRemoteBackendVersionConflict(b)
    45  
    46  	// Get the state
    47  	env, err := c.Workspace()
    48  	if err != nil {
    49  		c.Ui.Error(fmt.Sprintf("Error selecting workspace: %s", err))
    50  		return 1
    51  	}
    52  	stateMgr, err := b.StateMgr(env)
    53  	if err != nil {
    54  		c.Ui.Error(fmt.Sprintf(errStateLoadingState, err))
    55  		return 1
    56  	}
    57  	if err := stateMgr.RefreshState(); err != nil {
    58  		c.Ui.Error(fmt.Sprintf("Failed to load state: %s", err))
    59  		return 1
    60  	}
    61  
    62  	state := stateMgr.State()
    63  	if state == nil {
    64  		c.Ui.Error(errStateNotFound)
    65  		return 1
    66  	}
    67  
    68  	var addrs []addrs.AbsResourceInstance
    69  	var diags tfdiags.Diagnostics
    70  	if len(args) == 0 {
    71  		addrs, diags = c.lookupAllResourceInstanceAddrs(state)
    72  	} else {
    73  		addrs, diags = c.lookupResourceInstanceAddrs(state, args...)
    74  	}
    75  	if diags.HasErrors() {
    76  		c.showDiagnostics(diags)
    77  		return 1
    78  	}
    79  
    80  	for _, addr := range addrs {
    81  		if is := state.ResourceInstance(addr); is != nil {
    82  			if *lookupId == "" || *lookupId == states.LegacyInstanceObjectID(is.Current) {
    83  				c.Ui.Output(addr.String())
    84  			}
    85  		}
    86  	}
    87  
    88  	c.showDiagnostics(diags)
    89  
    90  	return 0
    91  }
    92  
    93  func (c *StateListCommand) Help() string {
    94  	helpText := `
    95  Usage: terraform [global options] state list [options] [address...]
    96  
    97    List resources in the Terraform state.
    98  
    99    This command lists resource instances in the Terraform state. The address
   100    argument can be used to filter the instances by resource or module. If
   101    no pattern is given, all resource instances are listed.
   102  
   103    The addresses must either be module addresses or absolute resource
   104    addresses, such as:
   105        aws_instance.example
   106        module.example
   107        module.example.module.child
   108        module.example.aws_instance.example
   109  
   110    An error will be returned if any of the resources or modules given as
   111    filter addresses do not exist in the state.
   112  
   113  Options:
   114  
   115    -state=statefile    Path to a Terraform state file to use to look
   116                        up Terraform-managed resources. By default, Terraform
   117                        will consult the state of the currently-selected
   118                        workspace.
   119  
   120    -id=ID              Filters the results to include only instances whose
   121                        resource types have an attribute named "id" whose value
   122                        equals the given id string.
   123  
   124  `
   125  	return strings.TrimSpace(helpText)
   126  }
   127  
   128  func (c *StateListCommand) Synopsis() string {
   129  	return "List resources in the state"
   130  }
   131  
   132  const errStateLoadingState = `Error loading the state: %[1]s
   133  
   134  Please ensure that your Terraform state exists and that you've
   135  configured it properly. You can use the "-state" flag to point
   136  Terraform at another state file.`
   137  
   138  const errStateNotFound = `No state file was found!
   139  
   140  State management commands require a state file. Run this command
   141  in a directory where Terraform has been run or use the -state flag
   142  to point the command to a specific state location.`