fleet/cmd/fleetctl/gitops.go
Victor Lyuboslavsky e4d5e27dd9
fleetctl gitops (#16535)
Add `fleetctl gitops` command for #13643 

Code review video:
https://www.loom.com/share/7941c51c709b44ccafd618dd05837d99?sid=27b923d7-1393-4396-bac7-30616b2d6de9

fleet-gitops PR that also needs review:
https://github.com/fleetdm/fleet-gitops/pull/26

Working global/team gitops configs that can be used for testing:
https://github.com/fleetdm/fleet-gitops/tree/victor/fixing-configs

# Checklist for submitter

If some of the following don't apply, delete the relevant line.

<!-- Note that API documentation changes are now addressed by the
product design team. -->

- [x] Changes file added for user-visible changes in `changes/` or
`orbit/changes/`.
- [x] Added/updated tests
- [x] Manual QA for all new/changed functionality
2024-02-09 13:34:57 -06:00

72 lines
1.7 KiB
Go

package main
import (
"errors"
"fmt"
"github.com/fleetdm/fleet/v4/pkg/spec"
"github.com/urfave/cli/v2"
"os"
"path/filepath"
)
func gitopsCommand() *cli.Command {
var (
flFilename string
flDryRun bool
)
return &cli.Command{
Name: "gitops",
Usage: "Synchronize Fleet configuration with provided file. This command is intended to be used in a GitOps workflow.",
UsageText: `fleetctl gitops [options]`,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "f",
EnvVars: []string{"FILENAME"},
Value: "",
Destination: &flFilename,
Usage: "The file with the GitOps configuration",
},
&cli.BoolFlag{
Name: "dry-run",
EnvVars: []string{"DRY_RUN"},
Destination: &flDryRun,
Usage: "Do not apply the file, just validate it",
},
configFlag(),
contextFlag(),
debugFlag(),
},
Action: func(c *cli.Context) error {
if flFilename == "" {
return errors.New("-f must be specified")
}
b, err := os.ReadFile(flFilename)
if err != nil {
return err
}
fleetClient, err := clientFromCLI(c)
if err != nil {
return err
}
baseDir := filepath.Dir(flFilename)
config, err := spec.GitOpsFromBytes(b, baseDir)
if err != nil {
return err
}
logf := func(format string, a ...interface{}) {
_, _ = fmt.Fprintf(c.App.Writer, format, a...)
}
err = fleetClient.DoGitOps(c.Context, config, baseDir, logf, flDryRun)
if err != nil {
return err
}
if flDryRun {
_, _ = fmt.Fprintf(c.App.Writer, "[!] gitops dry run succeeded\n")
} else {
_, _ = fmt.Fprintf(c.App.Writer, "[!] gitops succeeded\n")
}
return nil
},
}
}