github.com/ezbercih/terraform@v0.1.1-0.20140729011846-3c33865e0839/command/format_state.go (about)

     1  package command
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"sort"
     7  	"strings"
     8  
     9  	"github.com/hashicorp/terraform/terraform"
    10  	"github.com/mitchellh/colorstring"
    11  )
    12  
    13  // FormatState takes a state and returns a string
    14  func FormatState(s *terraform.State, c *colorstring.Colorize) string {
    15  	if c == nil {
    16  		panic("colorize not given")
    17  	}
    18  
    19  	if len(s.Resources) == 0 {
    20  		return "The state file is empty. No resources are represented."
    21  	}
    22  
    23  	buf := new(bytes.Buffer)
    24  	buf.WriteString("[reset]")
    25  
    26  	// First get the names of all the resources so we can show them
    27  	// in alphabetical order.
    28  	names := make([]string, 0, len(s.Resources))
    29  	for name, _ := range s.Resources {
    30  		names = append(names, name)
    31  	}
    32  	sort.Strings(names)
    33  
    34  	// Go through each resource and begin building up the output.
    35  	for _, k := range names {
    36  		rs := s.Resources[k]
    37  		id := rs.ID
    38  		if id == "" {
    39  			id = "<not created>"
    40  		}
    41  
    42  		taintStr := ""
    43  		if s.Tainted != nil {
    44  			if _, ok := s.Tainted[k]; ok {
    45  				taintStr = " (tainted)"
    46  			}
    47  		}
    48  
    49  		buf.WriteString(fmt.Sprintf("%s:%s\n", k, taintStr))
    50  		buf.WriteString(fmt.Sprintf("  id = %s\n", id))
    51  
    52  		// Sort the attributes
    53  		attrKeys := make([]string, 0, len(rs.Attributes))
    54  		for ak, _ := range rs.Attributes {
    55  			// Skip the id attribute since we just show the id directly
    56  			if ak == "id" {
    57  				continue
    58  			}
    59  
    60  			attrKeys = append(attrKeys, ak)
    61  		}
    62  		sort.Strings(attrKeys)
    63  
    64  		// Output each attribute
    65  		for _, ak := range attrKeys {
    66  			av := rs.Attributes[ak]
    67  			buf.WriteString(fmt.Sprintf("  %s = %s\n", ak, av))
    68  		}
    69  	}
    70  
    71  	if len(s.Outputs) > 0 {
    72  		buf.WriteString("\nOutputs:\n\n")
    73  
    74  		// Sort the outputs
    75  		ks := make([]string, 0, len(s.Outputs))
    76  		for k, _ := range s.Outputs {
    77  			ks = append(ks, k)
    78  		}
    79  		sort.Strings(ks)
    80  
    81  		// Output each output k/v pair
    82  		for _, k := range ks {
    83  			v := s.Outputs[k]
    84  			buf.WriteString(fmt.Sprintf("%s = %s\n", k, v))
    85  		}
    86  	}
    87  
    88  	return c.Color(strings.TrimSpace(buf.String()))
    89  }