Custom Flags



Introduction

Some commands (eg: provision) may require additional options. For instance, your application’s provision logic may require VPC subnets or EC2 SSH Key Names.

The default Sparta command line option flags may be extended and validated by building on the exposed Cobra command objects.

Adding Flags

To add a flag, use one of the pflag functions to register your custom flag with one of the standard CommandLineOption values.

For example:

// SSHKeyName is the SSH KeyName to use when provisioning new EC2 instance
var SSHKeyName string

func main() {
  // And add the SSHKeyName option to the provision step
  sparta.CommandLineOptions.Provision.Flags().StringVarP(&SSHKeyName,
    "key",
    "k",
    "",
    "SSH Key Name to use for EC2 instances")
}

Validating Input

Flags may be used to conditionalize which Sparta lambda functions are provided and/or their content. In this case, your application may first need to parse and validate the command line input before calling sparta.Main().

To validate user input, define a CommandLineOptionsHook function and provide it to sparta.ParseOptions. This function is called after the pflag bindings are invoked so that your application can validate user input.

The ParseOptions result is the optional error returned from your CommandLineOptionsHook function. If there is an error, your application can then exit with an application specific exit code. For instance:

// Define a validation hook s.t. we can verify the SSHKey is valid
validationHook := func(command *cobra.Command) error {
  if command.Name() == "provision" && len(SSHKeyName) <= 0 {
    return fmt.Errorf("SSHKeyName option is required")
  }
  return nil
  }
}
// Extract & validate the SSH Key
parseErr := sparta.ParseOptions(validationHook)
if nil != parseErr {
  os.Exit(3)
}

Sparta itself uses the govalidator package to simplify validating command line arguments. See sparta_main.go for an example.