/
gen_driftignore.go
81 lines (67 loc) · 2.25 KB
/
gen_driftignore.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package cmd
import (
"encoding/json"
"fmt"
"io"
"os"
"time"
"github.com/cloudskiff/driftctl/pkg/analyser"
"github.com/pkg/errors"
"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,
RunE: func(cmd *cobra.Command, args []string) error {
_, list, err := genDriftIgnore(opts)
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)
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.")
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)
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
}