github.com/kubernetes-incubator/kube-aws@v0.16.4/cmd/diff.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"strings"
     7  
     8  	"github.com/kubernetes-incubator/kube-aws/core/root"
     9  	"github.com/kubernetes-incubator/kube-aws/logger"
    10  	"github.com/spf13/cobra"
    11  )
    12  
    13  var (
    14  	cmdDiff = &cobra.Command{
    15  		Use:          "diff",
    16  		Short:        "Compare the current and the desired states of the cluster",
    17  		Long:         ``,
    18  		RunE:         runCmdDiff,
    19  		SilenceUsage: true,
    20  	}
    21  
    22  	diffOpts = struct {
    23  		awsDebug, prettyPrint, skipWait, export bool
    24  		context                                 int
    25  		profile                                 string
    26  		targets                                 []string
    27  	}{}
    28  )
    29  
    30  type ExitError struct {
    31  	msg  string
    32  	Code int
    33  }
    34  
    35  func (e *ExitError) Error() string {
    36  	return e.msg
    37  }
    38  
    39  func init() {
    40  	RootCmd.AddCommand(cmdDiff)
    41  	cmdDiff.Flags().BoolVar(&diffOpts.awsDebug, "aws-debug", false, "Log debug information from aws-sdk-go library")
    42  	cmdDiff.Flags().StringVar(&diffOpts.profile, "profile", "", "The AWS profile to use from credentials file")
    43  	cmdDiff.Flags().StringSliceVar(&diffOpts.targets, "targets", root.AllOperationTargetsAsStringSlice(), "Diff nothing but specified sub-stacks.  Specify `all` or any combination of `etcd`, `control-plane`, and node pool names. Defaults to `all`")
    44  	cmdDiff.Flags().IntVarP(&diffOpts.context, "context", "C", -1, "output NUM lines of context around changes")
    45  }
    46  
    47  func runCmdDiff(c *cobra.Command, _ []string) error {
    48  	opts := root.NewOptions(diffOpts.prettyPrint, diffOpts.skipWait, diffOpts.profile)
    49  
    50  	cluster, err := root.LoadClusterFromFile(configPath, opts, diffOpts.awsDebug)
    51  	if err != nil {
    52  		return fmt.Errorf("failed to read cluster config: %v", err)
    53  	}
    54  
    55  	targets := root.OperationTargetsFromStringSlice(diffOpts.targets)
    56  
    57  	if _, err := cluster.ValidateStack(targets); err != nil {
    58  		return err
    59  	}
    60  
    61  	diffs, err := cluster.Diff(targets, diffOpts.context)
    62  	if err != nil {
    63  		return fmt.Errorf("error comparing cluster states: %v", err)
    64  	}
    65  
    66  	for _, diff := range diffs {
    67  		logger.Infof("Detected changes in: %s\n%s", diff.Target, diff.String())
    68  	}
    69  
    70  	names := make([]string, len(diffs))
    71  	for i := range diffs {
    72  		names[i] = diffs[i].Target
    73  	}
    74  
    75  	if len(diffs) > 0 {
    76  		c.SilenceErrors = true
    77  		return &ExitError{fmt.Sprintf("Detected changes in: %s", strings.Join(names, ", ")), 2}
    78  	}
    79  
    80  	return nil
    81  }