forked from controlplaneio/simulator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.go
77 lines (64 loc) · 2.17 KB
/
init.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
package cmd
import (
"bufio"
"fmt"
"os"
"strings"
"github.com/kubernetes-simulator/simulator/pkg/simulator"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
func saveBucketConfig(logger *logrus.Logger, bucket string) {
logger.Info("Saving state bucket name to config")
viper.Set("state-bucket", bucket)
if err := viper.WriteConfig(); err != nil {
logger.WithFields(logrus.Fields{
"Error": err,
"BucketName": bucket,
}).Fatal("Unable to write config")
}
}
func newInitCommand() *cobra.Command {
cmd := &cobra.Command{
Use: `init`,
Short: "Creates and configures a bucket for remote state",
RunE: func(cmd *cobra.Command, args []string) error {
bucket := viper.GetString("state-bucket")
logger := newLogger(viper.GetString("loglevel"))
if bucket == "" {
logger.Info("No state bucket name found in config or on commandline arguments")
logger.Debug("Asking user for a name for the state bucket")
reader := bufio.NewReader(os.Stdin)
fmt.Print("Please choose a globally unique name for an S3 bucket to store the terraform state: ")
bucket, err := reader.ReadString('\n')
if err != nil {
return errors.Wrap(err, "Error reading bucket name from stdin")
}
bucket = strings.TrimSpace(bucket)
logger.WithFields(logrus.Fields{
"BucketName": bucket,
}).Info("Creating s3 bucket for terraform remote state")
if err = simulator.CreateRemoteStateBucket(logger, bucket); err != nil {
if strings.HasPrefix(errors.Cause(err).Error(), "BucketAlreadyOwnedByYou") {
logger.WithFields(logrus.Fields{
"BucketName": bucket,
}).Info("Bucket already exists and you own it")
saveBucketConfig(logger, bucket)
return nil
}
return errors.Wrapf(err, "Error creating s3 bucket %s", bucket)
}
saveBucketConfig(logger, bucket)
return nil
}
logger.WithFields(logrus.Fields{
"BucketName": bucket,
}).Warn("Simulator is already configured to use an S3 bucket")
logger.Warn("Please remove the state-bucket from simulator.yaml then exit and re-enter the container to create another")
return nil
},
}
return cmd
}