2021-05-04 15:08:54 +00:00
package cmd
import (
"encoding/json"
"fmt"
"os"
"github.com/cloudskiff/driftctl/pkg/analyser"
2021-05-18 10:09:50 +00:00
"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 {
2021-05-14 09:46:01 +00:00
Use : "gen-driftignore" ,
Short : "Generate a .driftignore file based on your scan result" ,
2021-06-05 11:09:47 +00:00
Long : "This command will generate a new .driftignore file containing your current drifts and send output to /dev/stdout\n\nExample: driftctl scan -o json://stdout | driftctl gen-driftignore -i /dev/stdin > .driftignore" ,
2021-05-14 09:46:01 +00:00
Args : cobra . NoArgs ,
2021-05-04 15:08:54 +00:00
RunE : func ( cmd * cobra . Command , args [ ] string ) error {
2021-05-18 10:09:50 +00:00
if opts . InputPath == "" {
2021-05-18 13:38:51 +00:00
return errors . New ( "Error: you must specify an input to parse JSON from. Use driftctl gen-driftignore -i <drifts.json>\nGenerate a JSON file using the output flag: driftctl scan -o json://path/to/drifts.json" )
2021-05-18 10:09:50 +00:00
}
2021-05-04 15:08:54 +00:00
_ , list , err := genDriftIgnore ( opts )
if err != nil {
return err
}
2021-09-02 16:18:06 +00:00
fmt . Println ( 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" )
2021-05-18 10:09:50 +00:00
fl . StringVarP ( & opts . InputPath , "input" , "i" , "" , "Input where the JSON should be parsed from" )
2021-05-04 15:08:54 +00:00
return cmd
}
func genDriftIgnore ( opts * analyser . GenDriftIgnoreOptions ) ( int , string , error ) {
input , err := os . ReadFile ( opts . InputPath )
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
}