2021-05-04 15:08:54 +00:00
package cmd
import (
"encoding/json"
"fmt"
2021-11-08 10:43:16 +00:00
"io"
2021-05-04 15:08:54 +00:00
"os"
2021-11-08 10:43:18 +00:00
"time"
2021-05-04 15:08:54 +00:00
"github.com/cloudskiff/driftctl/pkg/analyser"
2021-11-08 10:43:18 +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-11-08 10:43:18 +00:00
Long : "This command will generate a new .driftignore file containing your current drifts\n\nExample: driftctl scan -o json://stdout | driftctl gen-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-11-08 10:43:18 +00:00
_ , list , err := genDriftIgnore ( opts )
2021-05-04 15:08:54 +00:00
if err != nil {
return err
}
2021-11-08 10:43:18 +00:00
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" )
2021-11-08 10:43:16 +00:00
fl . StringVarP ( & opts . InputPath , "input" , "i" , "-" , "Input where the JSON should be parsed from. Defaults to stdin." )
2021-11-08 10:43:18 +00:00
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
}
2021-11-08 10:43:18 +00:00
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
}