github.com/nicgrayson/terraform@v0.4.3-0.20150415203910-c4de50829380/command/graph.go (about)

     1  package command
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"os"
     7  	"strings"
     8  
     9  	"github.com/hashicorp/terraform/terraform"
    10  )
    11  
    12  // GraphCommand is a Command implementation that takes a Terraform
    13  // configuration and outputs the dependency tree in graphical form.
    14  type GraphCommand struct {
    15  	Meta
    16  }
    17  
    18  func (c *GraphCommand) Run(args []string) int {
    19  	var moduleDepth int
    20  
    21  	args = c.Meta.process(args, false)
    22  
    23  	cmdFlags := flag.NewFlagSet("graph", flag.ContinueOnError)
    24  	cmdFlags.IntVar(&moduleDepth, "module-depth", 0, "module-depth")
    25  	cmdFlags.Usage = func() { c.Ui.Error(c.Help()) }
    26  	if err := cmdFlags.Parse(args); err != nil {
    27  		return 1
    28  	}
    29  
    30  	var path string
    31  	args = cmdFlags.Args()
    32  	if len(args) > 1 {
    33  		c.Ui.Error("The graph command expects one argument.\n")
    34  		cmdFlags.Usage()
    35  		return 1
    36  	} else if len(args) == 1 {
    37  		path = args[0]
    38  	} else {
    39  		var err error
    40  		path, err = os.Getwd()
    41  		if err != nil {
    42  			c.Ui.Error(fmt.Sprintf("Error getting pwd: %s", err))
    43  		}
    44  	}
    45  
    46  	ctx, _, err := c.Context(contextOpts{
    47  		Path:      path,
    48  		StatePath: "",
    49  	})
    50  	if err != nil {
    51  		c.Ui.Error(fmt.Sprintf("Error loading Terraform: %s", err))
    52  		return 1
    53  	}
    54  
    55  	g, err := ctx.Graph()
    56  	if err != nil {
    57  		c.Ui.Error(fmt.Sprintf("Error creating graph: %s", err))
    58  		return 1
    59  	}
    60  
    61  	c.Ui.Output(terraform.GraphDot(g, nil))
    62  
    63  	return 0
    64  }
    65  
    66  func (c *GraphCommand) Help() string {
    67  	helpText := `
    68  Usage: terraform graph [options] PATH
    69  
    70    Outputs the visual graph of Terraform resources. If the path given is
    71    the path to a configuration, the dependency graph of the resources are
    72    shown. If the path is a plan file, then the dependency graph of the
    73    plan itself is shown.
    74  
    75    The graph is outputted in DOT format. The typical program that can
    76    read this format is GraphViz, but many web services are also available
    77    to read this format.
    78  
    79  Options:
    80  
    81    -module-depth=n      The maximum depth to expand modules. By default this is
    82                         zero, which will not expand modules at all.
    83  
    84  `
    85  	return strings.TrimSpace(helpText)
    86  }
    87  
    88  func (c *GraphCommand) Synopsis() string {
    89  	return "Create a visual graph of Terraform resources"
    90  }