Documentation
¶
Index ¶
- Variables
- func CheckIfUpdateNeeded(outFile string, outStr string) bool
- func CleanOutputDir(outputFileMap map[string]bool, componentOutputDir string)
- func ConfigureLogger(debug bool)
- func Execute(ver string)
- func GenerateCommand(cmd *cobra.Command, args []string)
- func GenerateIncludesFiles(includesFiles []interface{}, kr8Spec types.Kr8ClusterSpec, config string, ...) map[string]bool
- func GetClusterParams() map[string]string
- func InitConfig()
- func ProcessFile(inputFile string, outputFile string, kr8Spec types.Kr8ClusterSpec, ...) string
- type CmdGenerateOptions
- type CmdGetOptions
- type CmdRenderOptions
- type CmdRootOptions
Constants ¶
This section is empty.
Variables ¶
var FormatCmd = &cobra.Command{ Use: "format [flags]", Short: "Format jsonnet files", Long: `Format jsonnet configuration files`, Args: cobra.MinimumNArgs(0), Run: func(cmd *cobra.Command, args []string) { // First get a list of all files in the base directory and subdirectories. Ignore .git directories. var fileList []string err := filepath.Walk(RootConfig.BaseDir, func(path string, info fs.FileInfo, err error) error { if info.IsDir() { if info.Name() == ".git" { return filepath.SkipDir } return nil } fileList = append(fileList, path) return nil }) util.FatalErrorCheck("Error walking the path "+RootConfig.BaseDir, err) fileList = util.Filter(fileList, func(s string) bool { var result bool for _, f := range strings.Split(cmdFormatFlags.Includes, ",") { t, _ := filepath.Match(f, s) if t { return t } result = result || t } return result }) fileList = util.Filter(fileList, func(s string) bool { var result bool for _, f := range strings.Split(cmdFormatFlags.Excludes, ",") { t, _ := filepath.Match(f, s) if t { return !t } result = result || t } return !result }) log.Debug().Msg("Filtered file list: " + fmt.Sprintf("%v", fileList)) log.Debug().Msg("Formatting files...") var waitGroup sync.WaitGroup parallel, err := cmd.Flags().GetInt("parallel") util.FatalErrorCheck("Error getting parallel flag", err) log.Debug().Msg("Parallel set to " + strconv.Itoa(parallel)) ants_file, _ := ants.NewPool(parallel) for _, filename := range fileList { waitGroup.Add(1) _ = ants_file.Submit(func() { defer waitGroup.Done() var bytes []byte bytes, err = os.ReadFile(filepath.Clean(filename)) output, err := formatter.Format(filename, string(bytes), util.GetDefaultFormatOptions()) if err != nil { fmt.Fprintln(os.Stderr, err.Error()) return } err = os.WriteFile(filepath.Clean(filename), []byte(output), 0600) if err != nil { fmt.Fprintln(os.Stderr, err.Error()) return } }) } waitGroup.Wait() }, }
var GenerateCmd = &cobra.Command{ Use: "generate [flags]", Short: "Generate components", Long: `Generate components in clusters`, Args: cobra.MinimumNArgs(0), Run: GenerateCommand, }
var GetClustersCmd = &cobra.Command{ Use: "clusters [flags]", Short: "Get all clusters", Long: "Get all clusters defined in kr8 config hierarchy", Run: func(cmd *cobra.Command, args []string) { clusters, err := util.GetClusterFilenames(RootConfig.ClusterDir) util.FatalErrorCheck("Error getting clusters", err) if cmdGetFlags.NoTable { for _, c := range clusters { println(c.Name + ": " + c.Path) } return } var entry []string table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Name", "Path"}) for _, c := range clusters { entry = append(entry, c.Name) entry = append(entry, c.Path) table.Append(entry) entry = entry[:0] } table.Render() }, }
var GetCmd = &cobra.Command{
Use: "get",
Short: "Display one or many kr8 resources",
Long: `Displays information about kr8 resources such as clusters and components`,
}
GetCmd represents the get command.
var GetComponentsCmd = &cobra.Command{ Use: "components [flags]", Short: "Get all components", Long: "Get all available components defined in the kr8 config hierarchy", Run: func(cmd *cobra.Command, args []string) { if cmdGetFlags.Cluster == "" && cmdGetFlags.ClusterParams == "" { log.Fatal().Msg("Please specify a --cluster name and/or --clusterparams file") } var params []string if cmdGetFlags.Cluster != "" { clusterPath := util.GetClusterPaths(RootConfig.ClusterDir, cmdGetFlags.Cluster) params = util.GetClusterParamsFilenames(RootConfig.ClusterDir, clusterPath) } if cmdGetFlags.ClusterParams != "" { params = append(params, cmdGetFlags.ClusterParams) } jvm := jnetvm.JsonnetRenderFiles(RootConfig.VMConfig, params, "._components", true, "", "components") if cmdGetFlags.ParamField != "" { value := gjson.Get(jvm, cmdGetFlags.ParamField) if value.String() == "" { log.Fatal().Msg("Error getting param: " + cmdGetFlags.ParamField) } else { formatted := util.Pretty(jvm, RootConfig.Color) fmt.Println(formatted) } } else { formatted := util.Pretty(jvm, RootConfig.Color) fmt.Println(formatted) } }, }
var GetParamsCmd = &cobra.Command{ Use: "params [flags]", Short: "Get parameter for components and clusters", Long: "Get parameters assigned to clusters and components in the kr8 config hierarchy", Run: func(cmd *cobra.Command, args []string) { if cmdGetFlags.Cluster == "" { log.Fatal().Msg("Please specify a --cluster") } var cList []string if cmdGetFlags.Component != "" { cList = append(cList, cmdGetFlags.Component) } params := jnetvm.JsonnetRenderClusterParams( RootConfig.VMConfig, cmdGetFlags.Cluster, cList, cmdGetFlags.ClusterParams, true, ) if cmdGetFlags.ParamField == "" { if cmdGetFlags.Component != "" { result := gjson.Get(params, cmdGetFlags.Component).String() fmt.Println(util.Pretty(result, RootConfig.Color)) } else { fmt.Println(util.Pretty(params, RootConfig.Color)) } return } if cmdGetFlags.ParamField != "" { value := gjson.Get(params, cmdGetFlags.ParamField) if value.String() == "" { log.Fatal().Msg("Error getting param: " + cmdGetFlags.ParamField) } fmt.Println(value) } }, }
var InitClusterCmd = &cobra.Command{ Use: "cluster [flags]", Short: "Init a new cluster config file", Long: "Initialize a new cluster configuration file", Run: func(cmd *cobra.Command, args []string) { cSpec := types.Kr8ClusterSpec{ Name: cmdInitFlags.ClusterName, ClusterDir: RootConfig.ClusterDir, PostProcessor: "function(input) input", GenerateDir: "generated", GenerateShortNames: false, PruneParams: false, } if cmdInitFlags.Interactive { prompt := &survey.Input{ Message: "Set the cluster name", Default: cmdInitFlags.ClusterName, Help: "Distinct name for the cluster", } util.FatalErrorCheck("Invalid cluster name", survey.AskOne(prompt, &cSpec.Name)) prompt = &survey.Input{ Message: "Set the cluster configuration directory", Default: RootConfig.ClusterDir, Help: "Set the root directory for the new cluster", } util.FatalErrorCheck("Invalid cluster directory", survey.AskOne(prompt, &cSpec.ClusterDir)) promptB := &survey.Confirm{ Message: "Generate short names for output file names?", Default: cSpec.GenerateShortNames, Help: "Shortens component names and file structure", } util.FatalErrorCheck("Invalid option", survey.AskOne(promptB, &cSpec.GenerateShortNames)) promptB = &survey.Confirm{ Message: "Prune component parameters?", Default: cSpec.PruneParams, Help: "This removes empty and null parameters from configuration", } util.FatalErrorCheck("Invalid option", survey.AskOne(promptB, &cSpec.PruneParams)) } util.FatalErrorCheck("Error generating cluster jsonnet file", kr8init.GenerateClusterJsonnet(cSpec, cSpec.ClusterDir)) }, }
var InitCmd = &cobra.Command{
Use: "init",
Short: "Initialize kr8 config repos, components and clusters",
Long: `kr8 requires specific directories and exists for its config to work.
This init command helps in creating directory structure for repos, clusters and
components`,
}
InitCmd represents the command. Various subcommands are available to initialize different components of kr8.
var InitComponentCmd = &cobra.Command{ Use: "component [flags]", Short: "Init a new component config file", Long: "Initialize a new component configuration file", Run: func(cmd *cobra.Command, args []string) { if cmdInitFlags.Interactive { prompt := &survey.Input{ Message: "Enter component name", Default: cmdInitFlags.ComponentName, Help: "Enter the name of the component you want to create", } util.FatalErrorCheck("Invalid component name", survey.AskOne(prompt, &cmdInitFlags.ComponentName)) prompt = &survey.Input{ Message: "Enter component directory", Default: RootConfig.ComponentDir, Help: "Enter the directory where you want to create the component", } util.FatalErrorCheck("Invalid component directory", survey.AskOne(prompt, &RootConfig.ComponentDir)) promptS := &survey.Select{ Message: "Select component type", Options: []string{"jsonnet", "yml", "tpl", "chart"}, Help: "Select the type of component you want to create", Default: "jsonnet", Description: func(value string, index int) string { switch value { case "jsonnet": return "Use a Jsonnet file to describe the component resources" case "yml": return "Use a yml (docker-compose) file to describe the component resources" case "tpl": return "Use a template file to describe the component resources" case "chart": return "Use a Helm chart to describe the component resources" default: return "" } }, } util.FatalErrorCheck("Invalid component type", survey.AskOne(promptS, &cmdInitFlags.ComponentType)) } util.FatalErrorCheck( "Error generating component jsonnet", kr8init.GenerateComponentJsonnet(cmdInitFlags, RootConfig.ComponentDir), ) }, }
var InitRepoCmd = &cobra.Command{ Use: "repo [flags] dir", Args: cobra.MinimumNArgs(1), Short: "Initialize a new kr8 config repo", Long: `Initialize a new kr8 config repo by downloading the kr8 config skeleton repo and initialize a git repo so you can get started`, Run: func(cmd *cobra.Command, args []string) { if len(args) == 0 { log.Fatal().Msg("Error: no directory specified") } outDir := args[len(args)-1] log.Debug().Msg("Initializing kr8 config repo in " + outDir) if cmdInitFlags.InitUrl != "" { util.FatalErrorCheck( "Issue fetching repo", util.FetchRepoUrl(cmdInitFlags.InitUrl, outDir, cmdInitFlags.Fetch), ) return } cmdInitOptions := kr8init.Kr8InitOptions{ InitUrl: cmdInitFlags.InitUrl, ClusterName: cmdInitFlags.ClusterName, ComponentName: "example-component", ComponentType: "jsonnet", Interactive: false, Fetch: false, } clusterOptions := types.Kr8ClusterSpec{ PostProcessor: "", GenerateDir: "generated", GenerateShortNames: false, PruneParams: false, ClusterDir: "clusters", Name: cmdInitFlags.ClusterName, } util.FatalErrorCheck( "Issue creating cluster.jsonnet", kr8init.GenerateClusterJsonnet(clusterOptions, outDir+"/clusters"), ) util.FatalErrorCheck( "Issue creating example component.jsonnet", kr8init.GenerateComponentJsonnet(cmdInitOptions, outDir+"/components"), ) util.FatalErrorCheck( "Issue creating lib folder", kr8init.GenerateLib(cmdInitFlags.Fetch, outDir+"/lib"), ) util.FatalErrorCheck( "Issue creating Readme.md", kr8init.GenerateReadme(outDir, cmdInitOptions, clusterOptions), ) }, }
Initializes a new kr8 configuration repository
Directory tree:
components/ clusters/ lib/ generated/
var JsonnetCmd = &cobra.Command{
Use: "jsonnet",
Short: "Jsonnet utilities",
Long: `Utility commands to process jsonnet`,
}
var JsonnetRenderCmd = &cobra.Command{ Use: "render [flags] file [file ...]", Short: "Render a jsonnet file", Long: `Render a jsonnet file to JSON or YAML`, Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { for _, f := range args { jvm.JsonnetRender(cmdFlagsJsonnet, f, RootConfig.VMConfig) } }, }
var RenderCmd = &cobra.Command{
Use: "render",
Short: "Render files",
Long: `Render files in jsonnet or YAML`,
}
var RenderHelmCmd = &cobra.Command{ Use: "helm", Short: "Clean YAML stream from Helm Template output - Reads from Stdin", Long: `Removes Null YAML objects from a YAML stream`, Run: func(cmd *cobra.Command, args []string) { decoder := yaml.NewYAMLReader(bufio.NewReader(os.Stdin)) jsa := [][]byte{} for { bytes, err := decoder.Read() if errors.Is(err, io.EOF) { break } else if err != nil { util.FatalErrorCheck("Error decoding yaml stream", err) } if len(bytes) == 0 { continue } jsonData, err := yaml.ToJSON(bytes) util.FatalErrorCheck("Error converting yaml to JSON", err) if string(jsonData) == "null" { continue } _, _, err = unstructured.UnstructuredJSONScheme.Decode(jsonData, nil, nil) util.FatalErrorCheck("Error handling unstructured JSON", err) jsa = append(jsa, jsonData) } for _, j := range jsa { out, err := goyaml.JSONToYAML(j) util.FatalErrorCheck("Error encoding JSON to YAML", err) fmt.Println("---") fmt.Println(string(out)) } }, }
var RenderJsonnetCmd = &cobra.Command{ Use: "jsonnet file [file ...]", Short: "Render a jsonnet file", Long: `Render a jsonnet file to JSON or YAML`, Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { for _, fileName := range args { jvm.JsonnetRender( types.CmdJsonnetOptions{ Prune: cmdRenderFlags.Prune, ClusterParams: cmdRenderFlags.ClusterParams, Cluster: cmdRenderFlags.Cluster, Component: cmdRenderFlags.ComponentName, Format: cmdRenderFlags.Format, Color: false, }, fileName, RootConfig.VMConfig) } }, }
var RootCmd = &cobra.Command{
Use: "kr8",
Short: "Kubernetes config parameter framework",
Long: `A tool to generate Kubernetes configuration from a hierarchy
of jsonnet files`,
}
RootCmd represents the base command when called without any subcommands.
var VersionCmd = &cobra.Command{ Use: "version", Short: "Return the current version of kr8", Long: `return the current version of kr8`, Run: func(cmd *cobra.Command, args []string) { fmt.Println(RootCmd.Use + " Plus Version: " + version) fmt.Println("jsonnet: github.com/google/go-jsonnet v0.20.0") fmt.Println("yml: github.com/ghodss/yaml v1.0.0") fmt.Println("template: github.com/Masterminds/sprig/v3 v3.2.3") fmt.Println("helm: github.com/grafana/tanka v0.27.1") fmt.Println("kompose: github.com/kubernetes/kompose v1.35.0") }, }
Print out versions of packages in use. Chore() - Updated manually.
Functions ¶
func CheckIfUpdateNeeded ¶
Check if a file needs updating based on its current contents and the new contents.
func CleanOutputDir ¶
func ConfigureLogger ¶ added in v0.0.2
func ConfigureLogger(debug bool)
func Execute ¶
func Execute(ver string)
Execute adds all child commands to the root command sets flags appropriately. This is called by main.main(). It only needs to happen once to the rootCmd.
func GenerateCommand ¶ added in v0.0.2
This function will generate the components for each cluster in parallel. It uses a wait group to ensure that all clusters have been processed before exiting.
func GenerateIncludesFiles ¶
func GetClusterParams ¶
func InitConfig ¶ added in v0.0.2
func InitConfig()
InitConfig reads in config file and ENV variables if set.
func ProcessFile ¶
func ProcessFile( inputFile string, outputFile string, kr8Spec types.Kr8ClusterSpec, componentName string, config string, incInfo types.Kr8ComponentSpecIncludeObject, jvm *jsonnet.VM, ) string
Process an includes file. Based on the extension, it will process it differently.
.jsonnet: Imported and processed using jsonnet VM.
.yml, .yaml: Imported and processed through native function ParseYaml.
.tpl, .tmpl: Processed using component config and Sprig templating.
Types ¶
type CmdGenerateOptions ¶ added in v0.0.2
type CmdGenerateOptions struct {
// Stores the path to the cluster params file
ClusterParamsFile string
// Stores the output directory for generated files
GenerateDir string
// Stores the filters to apply to clusters and components when generating files
Filters util.PathFilterOptions
}
Stores the options for the 'generate' command.
type CmdGetOptions ¶
type CmdGetOptions struct {
// ClusterParams provides a way to provide cluster params as a single file.
// This can be combined with --cluster to override the cluster.
ClusterParams string
// If true, just prints result instead of placing in table
NoTable bool
// Field to display from the resource
FieldName string
// Cluster to get resources from
Cluster string
// Component to get resources from
Component string
// Param to display from the resource
ParamField string
}
Holds the options for the get command.
type CmdRenderOptions ¶ added in v0.0.2
type CmdRenderOptions struct {
// Prune null and empty objects from rendered json
Prune bool
// Filename to read cluster configuration from
ClusterParams string
// Name of the component to render
ComponentName string
// Name of the cluster to render
Cluster string
// Format of the output (yaml, json or stream)
Format string
}
Contains parameters for the kr8 render command.
type CmdRootOptions ¶ added in v0.0.2
type CmdRootOptions struct {
// kr8 config base directory
BaseDir string
// kr8 cluster directory
ClusterDir string
// kr8 component directory
ComponentDir string
// A config file with kr8 configuration
ConfigFile string
// parallelism - defaults to runtime.GOMAXPROCS(0)
Parallel int
// log more information about what kr8 is doing. Overrides --loglevel
Debug bool
// set log level
LogLevel string
// enable colorized output (default true). Set to false to disable")
Color bool
// contains ingormation to configure jsonnet vm
VMConfig types.VMConfig
}
Default options that are available to all commands.
var RootConfig CmdRootOptions