driftctl/pkg/cmd/gen_driftignore.go

82 lines
2.3 KiB
Go
Raw Normal View History

2021-05-04 15:08:54 +00:00
package cmd
import (
"encoding/json"
"fmt"
"io"
2021-05-04 15:08:54 +00:00
"os"
"time"
2021-05-04 15:08:54 +00:00
"github.com/cloudskiff/driftctl/pkg/analyser"
"github.com/pkg/errors"
2021-05-04 15:08:54 +00:00
"github.com/spf13/cobra"
)
func NewGenDriftIgnoreCmd() *cobra.Command {
opts := &analyser.GenDriftIgnoreOptions{}
cmd := &cobra.Command{
Use: "gen-driftignore",
Short: "Generate a .driftignore file based on your scan result",
Long: "This command will generate a new .driftignore file containing your current drifts\n\nExample: driftctl scan -o json://stdout | driftctl gen-driftignore",
Args: cobra.NoArgs,
2021-05-04 15:08:54 +00:00
RunE: func(cmd *cobra.Command, args []string) error {
_, list, err := genDriftIgnore(opts)
2021-05-04 15:08:54 +00:00
if err != nil {
return err
}
ignoreFile := os.Stdout
if opts.OutputPath != "-" {
var err error
ignoreFile, err = os.OpenFile(opts.OutputPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return errors.Errorf("error opening output file: %s", err)
}
defer ignoreFile.Close()
fmt.Fprintf(os.Stderr, "Appending ignore rules to %s\n", opts.OutputPath)
}
fmt.Fprintf(ignoreFile, "# Generated by gen-driftignore cmd @ %s\n%s\n", time.Now().Format(time.RFC1123), list)
2021-05-04 15:08:54 +00:00
return nil
},
}
fl := cmd.Flags()
fl.BoolVar(&opts.ExcludeUnmanaged, "exclude-unmanaged", false, "Exclude resources not managed by IaC")
fl.BoolVar(&opts.ExcludeDeleted, "exclude-missing", false, "Exclude missing resources")
fl.BoolVar(&opts.ExcludeDrifted, "exclude-changed", false, "Exclude resources that changed on cloud provider")
fl.StringVarP(&opts.InputPath, "input", "i", "-", "Input where the JSON should be parsed from. Defaults to stdin.")
fl.StringVarP(&opts.OutputPath, "output", "o", ".driftignore", "Output file path to write the driftignore to.")
2021-05-04 15:08:54 +00:00
return cmd
}
func genDriftIgnore(opts *analyser.GenDriftIgnoreOptions) (int, string, error) {
driftFile := os.Stdin
if opts.InputPath != "-" {
var err error
driftFile, err = os.Open(opts.InputPath)
if err != nil {
return 0, "", err
}
defer driftFile.Close()
}
input, err := io.ReadAll(driftFile)
2021-05-04 15:08:54 +00:00
if err != nil {
return 0, "", err
}
analysis := &analyser.Analysis{}
err = json.Unmarshal(input, analysis)
if err != nil {
return 0, "", err
}
n, list := analysis.DriftIgnoreList(*opts)
return n, list, nil
}