diff --git a/cmd/cluster.go b/cmd/cluster.go index 2905bbc..5a53a63 100644 --- a/cmd/cluster.go +++ b/cmd/cluster.go @@ -1,44 +1,29 @@ package cmd import ( - "fmt" - "os" - "path/filepath" "strings" "github.com/urfave/cli/v2" - "go.uber.org/zap" "rmk/config" "rmk/util" ) -type StateRunner interface { - clusterStateDelete() error - clusterStateList() error - clusterStateRefresh() error -} - type ClusterCommands struct { - Conf *config.Config - Ctx *cli.Context - SpecCMDs []*util.SpecCMD - PlanFile string - WorkDir string + *ReleaseCommands } -func (cc *ClusterCommands) clusterRootDir() (string, error) { - for _, provider := range cc.Conf.Clusters { - if strings.HasPrefix(provider.Name, cc.Conf.ClusterProvider) { - return provider.DstPath, nil - } - } - - return "", fmt.Errorf("destination path for cluster provider %s not found", cc.Conf.ClusterProvider) +func newClusterCommands(conf *config.Config, ctx *cli.Context, workDir string) *ClusterCommands { + return &ClusterCommands{&ReleaseCommands{Conf: conf, Ctx: ctx, WorkDir: workDir}} } func (cc *ClusterCommands) awsEks() *util.SpecCMD { return &util.SpecCMD{ + Envs: []string{ + "AWS_PROFILE=" + cc.Conf.Profile, + "AWS_CONFIG_FILE=" + strings.Join(cc.Conf.AWSSharedConfigFile(cc.Conf.Profile), ""), + "AWS_SHARED_CREDENTIALS_FILE=" + strings.Join(cc.Conf.AWSSharedCredentialsFile(cc.Conf.Profile), ""), + }, Args: []string{"eks", "--region", cc.Conf.Region, "update-kubeconfig", @@ -54,453 +39,9 @@ func (cc *ClusterCommands) awsEks() *util.SpecCMD { } } -func (cc *ClusterCommands) runBatchCMD() error { - if err := os.Unsetenv("AWS_PROFILE"); err != nil { - return err - } - - for _, val := range cc.SpecCMDs { - val.Envs = []string{ - "AWS_PROFILE=" + cc.Conf.Profile, - "AWS_CONFIG_FILE=" + strings.Join(cc.Conf.AWSSharedConfigFile(cc.Conf.Profile), ""), - "AWS_SHARED_CREDENTIALS_FILE=" + strings.Join(cc.Conf.AWSSharedCredentialsFile(cc.Conf.Profile), ""), - } - if err := val.AddEnv(); err != nil { - return err - } - - if err := val.ExecCMD(); err != nil { - if val.Debug { - zap.S().Debugf("command: %s", val.CommandStr) - zap.S().Debugf("path: %s", val.Dir) - for _, v := range val.Envs { - zap.S().Debugf("env: %s", v) - } - } - - return err - } - - if val.Debug { - zap.S().Debugf("command: %s", val.CommandStr) - zap.S().Debugf("path: %s", val.Dir) - for _, v := range val.Envs { - zap.S().Debugf("env: %s", v) - } - } - } - - return nil -} - -func (cc *ClusterCommands) initialize() *util.SpecCMD { - args := []string{ - "init", - "-backend=true", - "-backend-config=region=" + cc.Conf.Region, - "-backend-config=bucket=" + cc.Conf.Terraform.BucketName, - "-backend-config=key=" + cc.Conf.Terraform.BucketKey, - } - if cc.Conf.ClusterProvisionerSL { - args = append(args, "-backend-config=dynamodb_table="+cc.Conf.Terraform.DDBTableName) - } - - args = append(args, "-reconfigure") - return &util.SpecCMD{ - Args: args, - Command: "terraform", - Ctx: cc.Ctx.Context, - Dir: cc.WorkDir, - Debug: true, - } -} - -func (cc *ClusterCommands) validate() *util.SpecCMD { - return &util.SpecCMD{ - Args: []string{"validate"}, - Command: "terraform", - Ctx: cc.Ctx.Context, - Dir: cc.WorkDir, - Debug: true, - } -} - -func (cc *ClusterCommands) workspace(args ...string) *util.SpecCMD { - return &util.SpecCMD{ - Args: append([]string{"workspace"}, args...), - Command: "terraform", - Ctx: cc.Ctx.Context, - Dir: cc.WorkDir, - Debug: true, - } -} - -func (cc *ClusterCommands) output(args ...string) *util.SpecCMD { - return &util.SpecCMD{ - Args: append([]string{"output"}, args...), - Command: "terraform", - Ctx: cc.Ctx.Context, - Dir: cc.WorkDir, - DisableStdOut: true, - Debug: false, - } -} - -func (cc *ClusterCommands) destroy() *util.SpecCMD { - return &util.SpecCMD{ - Args: []string{"destroy", "-auto-approve", - "-var=aws_account_id=" + cc.Conf.AccountID, - "-var=cloudflare_api_token=" + cc.Conf.CloudflareToken, - "-var=name=" + cc.Conf.Name, - "-var=region=" + cc.Conf.Region, - "-var=root_domain=" + cc.Conf.RootDomain, - "-var=terraform_bucket_key=" + cc.Conf.Terraform.BucketKey, - "-var=terraform_bucket_name=" + cc.Conf.Terraform.BucketName, - }, - Command: "terraform", - Ctx: cc.Ctx.Context, - Dir: cc.WorkDir, - Debug: true, - } -} - -func (cc *ClusterCommands) plan() *util.SpecCMD { - return &util.SpecCMD{ - Args: []string{ - "plan", - "-out=" + cc.PlanFile, - "-var=aws_account_id=" + cc.Conf.AccountID, - "-var=cloudflare_api_token=" + cc.Conf.CloudflareToken, - "-var=name=" + cc.Conf.Name, - "-var=region=" + cc.Conf.Region, - "-var=root_domain=" + cc.Conf.RootDomain, - "-var=terraform_bucket_key=" + cc.Conf.Terraform.BucketKey, - "-var=terraform_bucket_name=" + cc.Conf.Terraform.BucketName, - }, - Command: "terraform", - Ctx: cc.Ctx.Context, - Dir: cc.WorkDir, - Debug: true, - } -} - -func (cc *ClusterCommands) apply() *util.SpecCMD { - return &util.SpecCMD{ - Args: []string{"apply", cc.PlanFile}, - Command: "terraform", - Ctx: cc.Ctx.Context, - Dir: cc.WorkDir, - Debug: true, - } -} - -func (cc *ClusterCommands) listResources() *util.SpecCMD { - return &util.SpecCMD{ - Args: []string{"state", "list"}, - Command: "terraform", - Ctx: cc.Ctx.Context, - Dir: cc.WorkDir, - Debug: true, - } -} - -func (cc *ClusterCommands) refresh() *util.SpecCMD { - return &util.SpecCMD{ - Args: []string{"refresh", - "-var=aws_account_id=" + cc.Conf.AccountID, - "-var=cloudflare_api_token=" + cc.Conf.CloudflareToken, - "-var=name=" + cc.Conf.Name, - "-var=region=" + cc.Conf.Region, - "-var=root_domain=" + cc.Conf.RootDomain, - "-var=terraform_bucket_key=" + cc.Conf.Terraform.BucketKey, - "-var=terraform_bucket_name=" + cc.Conf.Terraform.BucketName, - }, - Command: "terraform", - Ctx: cc.Ctx.Context, - Dir: cc.WorkDir, - Debug: true, - } -} - -func (cc *ClusterCommands) state(args ...string) *util.SpecCMD { - return &util.SpecCMD{ - Args: append([]string{"state"}, args...), - Command: "terraform", - Ctx: cc.Ctx.Context, - Dir: cc.WorkDir, - Debug: true, - } -} - -func (cc *ClusterCommands) clusterContext() error { - cc.SpecCMDs = append(cc.SpecCMDs, cc.awsEks()) - return cc.runBatchCMD() -} - -func (cc *ClusterCommands) clusterDestroy() error { - checkWorkspace, err := cc.Conf.BucketKeyExists("", cc.Conf.Terraform.BucketName, "env:/"+cc.Conf.Name+"/tf.tfstate") - if err != nil { - return err - } - - if checkWorkspace { - cc.SpecCMDs = append(cc.SpecCMDs, cc.initialize(), cc.validate(), cc.workspace("select", cc.Conf.Name)) - if err := cc.runBatchCMD(); err != nil { - return err - } - - destroy := cc.destroy() - - match, err := util.WalkMatch( - util.GetPwdPath(util.TenantValuesDIR, "clusters", util.AWSClusterProvider, cc.Conf.Environment), - "*."+util.TerraformVarsExt, - ) - if err != nil { - return err - } - - for _, val := range match { - destroy.Args = append(destroy.Args, "-var-file="+val) - } - - if err := os.RemoveAll(cc.PlanFile); err != nil { - return err - } - - cc.SpecCMDs = append([]*util.SpecCMD{}, destroy, cc.workspace("select", "default"), - cc.workspace("delete", cc.Conf.Name)) - - return cc.runBatchCMD() - } else { - zap.S().Infof("Terraform cluster in workspace %s already deleted or not created", cc.Conf.Name) - return nil - } -} - -func (cc *ClusterCommands) clusterList() error { - cc.SpecCMDs = append(cc.SpecCMDs, cc.initialize(), cc.workspace("list")) - return cc.runBatchCMD() -} - -func (cc *ClusterCommands) clusterProvision() error { - var workspace *util.SpecCMD - - if err := os.MkdirAll(filepath.Join(cc.WorkDir, "plans"), 0755); err != nil { - zap.S().Fatal(err) - } - - checkWorkspace, err := cc.Conf.BucketKeyExists("", cc.Conf.Terraform.BucketName, "env:/"+cc.Conf.Name+"/tf.tfstate") - if err != nil { - zap.S().Fatal(err) - } - - if checkWorkspace { - workspace = cc.workspace("select", cc.Conf.Name) - } else { - workspace = cc.workspace("new", cc.Conf.Name) - } - - plan := cc.plan() - - match, err := util.WalkMatch( - util.GetPwdPath(util.TenantValuesDIR, "clusters", util.AWSClusterProvider, cc.Conf.Environment), - "*."+util.TerraformVarsExt, - ) - - for _, val := range match { - plan.Args = append(plan.Args, "-var-file="+val) - } - - if cc.Ctx.Bool("plan") { - cc.SpecCMDs = append(cc.SpecCMDs, cc.initialize(), cc.validate(), workspace, plan) - return cc.runBatchCMD() - } - - cc.SpecCMDs = append(cc.SpecCMDs, cc.initialize(), cc.validate(), workspace, plan, cc.apply()) - if err := cc.runBatchCMD(); err != nil { - return err - } - - rc := &ReleaseCommands{ - Conf: cc.Conf, - Ctx: cc.Ctx, - WorkDir: util.GetPwdPath(""), - UpdateContext: true, - } - - return rc.releaseKubeContext() -} - -func (cc *ClusterCommands) clusterStateDelete() error { - cc.SpecCMDs = append(cc.SpecCMDs, cc.state("rm", cc.Ctx.String("resource-address"))) - - return cc.runBatchCMD() -} - -func (cc *ClusterCommands) clusterStateList() error { - cc.SpecCMDs = append(cc.SpecCMDs, cc.state(cc.Ctx.Command.Name)) - - return cc.runBatchCMD() -} - -func (cc *ClusterCommands) clusterStateRefresh() error { - var workspace *util.SpecCMD - - checkWorkspace, err := cc.Conf.BucketKeyExists("", cc.Conf.Terraform.BucketName, "env:/"+cc.Conf.Name+"/tf.tfstate") - if err != nil { - zap.S().Fatal(err) - } - - if checkWorkspace { - workspace = cc.workspace("select", cc.Conf.Name) - } else { - workspace = cc.workspace("new", cc.Conf.Name) - } - - refresh := cc.refresh() - match, err := util.WalkMatch( - util.GetPwdPath(util.TenantValuesDIR, "clusters", util.AWSClusterProvider, cc.Conf.Environment), - "*."+util.TerraformVarsExt, - ) - if err != nil { - return err - } - - for _, val := range match { - refresh.Args = append(refresh.Args, "-var-file="+val) - } - - cc.SpecCMDs = append(cc.SpecCMDs, cc.initialize(), cc.validate(), workspace, refresh) - - return cc.runBatchCMD() -} - -func clusterDestroyAction(conf *config.Config) cli.ActionFunc { - return func(c *cli.Context) error { - if err := util.ValidateGitHubToken(c, ""); err != nil { - return err - } - - if err := util.ValidateNArg(c, 0); err != nil { - return err - } - - if err := resolveDependencies(conf.InitConfig(false), c, false); err != nil { - return err - } - - cc := &ClusterCommands{ - Conf: conf, - Ctx: c, - } - - if pkgDst, err := cc.clusterRootDir(); err != nil { - return err - } else { - cc.WorkDir = filepath.Join(pkgDst, "terraform") - } - - cc.PlanFile = filepath.Join(cc.WorkDir, "plans", conf.Name+"__"+conf.Environment+".tfplan") - - return cc.clusterDestroy() - } -} - -func clusterListAction(conf *config.Config) cli.ActionFunc { - return func(c *cli.Context) error { - if err := util.ValidateGitHubToken(c, ""); err != nil { - return err - } - - if err := util.ValidateNArg(c, 0); err != nil { - return err - } - - if err := resolveDependencies(conf.InitConfig(false), c, false); err != nil { - return err - } - - cc := &ClusterCommands{ - Conf: conf, - Ctx: c, - } - - if pkgDst, err := cc.clusterRootDir(); err != nil { - return err - } else { - cc.WorkDir = filepath.Join(pkgDst, "terraform") - } - - return cc.clusterList() - } -} - -func clusterProvisionAction(conf *config.Config) cli.ActionFunc { - return func(c *cli.Context) error { - if err := util.ValidateGitHubToken(c, ""); err != nil { - return err - } - - if err := util.ValidateNArg(c, 0); err != nil { - return err - } - - if err := resolveDependencies(conf.InitConfig(true), c, false); err != nil { - return err - } - - cc := &ClusterCommands{ - Conf: conf, - Ctx: c, - } - - if pkgDst, err := cc.clusterRootDir(); err != nil { - return err - } else { - cc.WorkDir = filepath.Join(pkgDst, "terraform") - } - - cc.PlanFile = filepath.Join(cc.WorkDir, "plans", conf.Name+"__"+conf.Environment+".tfplan") - - if err := cc.clusterProvision(); err != nil { - return err - } - - if err := conf.GetTerraformOutputs(); err != nil { - return err - } - - return conf.CreateConfigFile() - } -} - -func clusterStateAction(conf *config.Config, action func(stateRunner StateRunner) error) cli.ActionFunc { - return func(c *cli.Context) error { - if err := util.ValidateGitHubToken(c, ""); err != nil { - return err - } - - if err := util.ValidateNArg(c, 0); err != nil { - return err - } - - if err := resolveDependencies(conf.InitConfig(false), c, false); err != nil { - return err - } - - cc := &ClusterCommands{ - Conf: conf, - Ctx: c, - } - - if pkgDst, err := cc.clusterRootDir(); err != nil { - return err - } else { - cc.WorkDir = filepath.Join(pkgDst, "terraform") - } - - return action(cc) - } +func (cc *ClusterCommands) awsClusterContext() error { + cc.SpecCMD = cc.awsEks() + return runner(cc).runCMD() } func clusterSwitchAction(conf *config.Config) cli.ActionFunc { @@ -513,7 +54,7 @@ func clusterSwitchAction(conf *config.Config) cli.ActionFunc { return err } - if err := resolveDependencies(conf.InitConfig(false), c, false); err != nil { + if err := resolveDependencies(conf.InitConfig(), c, false); err != nil { return err } diff --git a/cmd/commands.go b/cmd/commands.go index ad55098..db67807 100644 --- a/cmd/commands.go +++ b/cmd/commands.go @@ -24,11 +24,8 @@ func Commands() []*cli.Command { }, } flags := Flags{ - "clusterCRLogin": flagsClusterCRLogin(), "clusterK3DCreate": flagsClusterK3DCreate(), "clusterK3DImport": flagsClusterK3DImport(), - "clusterPlan": flagsClusterPlan(), - "clusterStateDelete": flagsClusterStateDelete(), "clusterSwitch": flagsClusterSwitch(), "config": flagsConfig(), "configList": flagsConfigList(), @@ -112,51 +109,33 @@ func Commands() []*cli.Command { Usage: "Cluster management", Subcommands: []*cli.Command{ { - Name: "container-registry", - Usage: "Container registry management", + Name: "capi", + Usage: "CAPI cluster management", Aliases: []string{"c"}, Category: "cluster", Subcommands: []*cli.Command{ { - Name: "login", - Usage: "Log in to container registry", - Before: readInputSourceWithContext(gitSpec, conf, flags["clusterCRLogin"]), - Flags: flags["clusterCRLogin"], - Category: "container-registry", + Name: "create", + Usage: "Create CAPI cluster", + Aliases: []string{"c"}, + Before: readInputSourceWithContext(gitSpec, conf, flags["clusterK3DCreate"]), + Flags: flags["clusterK3DCreate"], + Category: "capi", BashComplete: util.ShellCompleteCustomOutput, - Action: containerRegistryAction(conf, DockerRunner.dockerLogin), + Action: K3DCreateAction(conf), }, { - Name: "logout", - Usage: "Log out from container registry", + Name: "delete", + Usage: "Delete CAPI cluster", + Aliases: []string{"d"}, Before: readInputSourceWithContext(gitSpec, conf, flags["hidden"]), Flags: flags["hidden"], - Category: "container-registry", + Category: "capi", BashComplete: util.ShellCompleteCustomOutput, - Action: containerRegistryAction(conf, DockerRunner.dockerLogout), + Action: K3DAction(conf, K3DRunner.createDeleteK3DCluster), }, }, }, - { - Name: "destroy", - Usage: "Destroy AWS cluster using Terraform", - Aliases: []string{"d"}, - Before: readInputSourceWithContext(gitSpec, conf, flags["hidden"]), - Flags: flags["hidden"], - Category: "cluster", - BashComplete: util.ShellCompleteCustomOutput, - Action: clusterDestroyAction(conf), - }, - { - Name: "list", - Usage: "List all Terraform available workspaces", - Aliases: []string{"l"}, - Before: readInputSourceWithContext(gitSpec, conf, flags["hidden"]), - Flags: flags["hidden"], - Category: "cluster", - BashComplete: util.ShellCompleteCustomOutput, - Action: clusterListAction(conf), - }, { Name: "k3d", Usage: "K3D cluster management", @@ -224,54 +203,6 @@ func Commands() []*cli.Command { }, }, }, - { - Name: "provision", - Usage: "Provision AWS cluster using Terraform", - Aliases: []string{"p"}, - Before: readInputSourceWithContext(gitSpec, conf, flags["clusterPlan"]), - Flags: flags["clusterPlan"], - Category: "cluster", - BashComplete: util.ShellCompleteCustomOutput, - Action: clusterProvisionAction(conf), - }, - { - Name: "state", - Usage: "State cluster management using Terraform", - Aliases: []string{"t"}, - Category: "cluster", - Subcommands: []*cli.Command{ - { - Name: "delete", - Usage: "Delete resource from Terraform state", - Aliases: []string{"d"}, - Before: readInputSourceWithContext(gitSpec, conf, flags["clusterStateDelete"]), - Flags: flags["clusterStateDelete"], - Category: "state", - BashComplete: util.ShellCompleteCustomOutput, - Action: clusterStateAction(conf, StateRunner.clusterStateDelete), - }, - { - Name: "list", - Usage: "List resources from Terraform state", - Aliases: []string{"l"}, - Before: readInputSourceWithContext(gitSpec, conf, flags["hidden"]), - Flags: flags["hidden"], - Category: "state", - BashComplete: util.ShellCompleteCustomOutput, - Action: clusterStateAction(conf, StateRunner.clusterStateList), - }, - { - Name: "refresh", - Usage: "Update state file for AWS cluster using Terraform", - Aliases: []string{"r"}, - Before: readInputSourceWithContext(gitSpec, conf, flags["hidden"]), - Flags: flags["hidden"], - Category: "state", - BashComplete: util.ShellCompleteCustomOutput, - Action: clusterStateAction(conf, StateRunner.clusterStateRefresh), - }, - }, - }, { Name: "switch", Usage: "Switch Kubernetes context for tenant cluster", diff --git a/cmd/config.go b/cmd/config.go index c640afd..5fb209f 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -374,8 +374,6 @@ func getConfigFromEnvironment(c *cli.Context, conf *config.Config, gitSpec *git_ } if c.String("cluster-provider") == util.AWSClusterProvider { - conf.AwsConfigure = new(aws_provider.AwsConfigure) - if err := c.Set("config-name-from", conf.Name); err != nil { return err } @@ -458,7 +456,6 @@ func getConfigFromEnvironment(c *cli.Context, conf *config.Config, gitSpec *git_ } conf.ConfigNameFrom = c.String("config-name-from") - conf.CloudflareToken = c.String("cloudflare-token") conf.GitHubToken = c.String("github-token") return nil @@ -535,14 +532,9 @@ func configInitAction(conf *config.Config, gitSpec *git_handler.GitSpec) cli.Act switch conf.ClusterProvider { case util.AWSClusterProvider: - conf.Terraform.BucketKey = util.TenantBucketKey - conf.ClusterProvisionerSL = c.Bool("cluster-provisioner-state-locking") conf.AwsConfigure.Profile = gitSpec.ID conf.AWSMFAProfile = c.String("aws-mfa-profile") conf.AWSMFATokenExpiration = c.String("aws-mfa-token-expiration") - conf.AWSECRHost = c.String("aws-ecr-host") - conf.AWSECRRegion = c.String("aws-ecr-region") - conf.AWSECRUserName = c.String("aws-ecr-user-name") // AWS Profile init configuration with support MFA if err := initAWSProfile(c, conf, gitSpec); err != nil { @@ -554,13 +546,12 @@ func configInitAction(conf *config.Config, gitSpec *git_handler.GitSpec) cli.Act awsUID := conf.AccountID[0:3] + conf.AccountID[len(conf.AccountID)-2:] conf.SopsAgeKeys = util.GetHomePath(util.RMKDir, util.SopsRootName, conf.Tenant+"-"+util.SopsRootName+"-"+awsUID) conf.SopsBucketName = conf.Tenant + "-" + util.SopsRootName + "-" + awsUID - conf.Terraform.BucketName = conf.Tenant + "-" + util.TenantBucketName + "-" + awsUID - conf.Terraform.DDBTableName = util.TenantDDBTablePrefix + "-" + awsUID case util.LocalClusterProvider: + conf.AwsConfigure = &aws_provider.AwsConfigure{} conf.SopsAgeKeys = util.GetHomePath(util.RMKDir, util.SopsRootName, conf.Tenant+"-"+util.SopsRootName+"-"+util.LocalClusterProvider) } - if err := conf.InitConfig(true).SetRootDomain(c, gitSpec.ID); err != nil { + if err := conf.InitConfig().SetRootDomain(c, gitSpec.ID); err != nil { return err } @@ -569,18 +560,6 @@ func configInitAction(conf *config.Config, gitSpec *git_handler.GitSpec) cli.Act } if conf.ClusterProvider == util.AWSClusterProvider { - if conf.ClusterProvisionerSL { - // create dynamodb table for backend terraform - if err := conf.CreateDynamoDBTable(conf.Terraform.DDBTableName); err != nil { - return err - } - } - - // create s3 bucket for backend terraform - if err := conf.CreateBucket(conf.Terraform.BucketName); err != nil { - return err - } - //create s3 bucket for sops age keys if err := conf.CreateBucket(conf.SopsBucketName); err != nil { return err @@ -590,7 +569,7 @@ func configInitAction(conf *config.Config, gitSpec *git_handler.GitSpec) cli.Act return err } - if err := resolveDependencies(conf.InitConfig(true), c, false); err != nil { + if err := resolveDependencies(conf.InitConfig(), c, false); err != nil { return err } @@ -599,7 +578,7 @@ func configInitAction(conf *config.Config, gitSpec *git_handler.GitSpec) cli.Act return nil } - if err := resolveDependencies(conf.InitConfig(false), c, false); err != nil { + if err := resolveDependencies(conf.InitConfig(), c, false); err != nil { return err } diff --git a/cmd/container_registry.go b/cmd/container_registry.go deleted file mode 100644 index f690dac..0000000 --- a/cmd/container_registry.go +++ /dev/null @@ -1,91 +0,0 @@ -package cmd - -import ( - "fmt" - "strings" - - "github.com/urfave/cli/v2" - "go.uber.org/zap" - - "rmk/config" - "rmk/util" -) - -type DockerRunner interface { - dockerLogin() error - dockerLogout() error -} - -type CRCommands struct { - *ReleaseCommands -} - -func newCRCommands(conf *config.Config, ctx *cli.Context, workDir string) *CRCommands { - return &CRCommands{&ReleaseCommands{Conf: conf, Ctx: ctx, WorkDir: workDir}} -} - -func (cr *CRCommands) docker(args ...string) *util.SpecCMD { - return &util.SpecCMD{ - Args: append([]string{}, args...), - Command: "docker", - Dir: cr.WorkDir, - Ctx: cr.Ctx.Context, - DisableStdOut: true, - Debug: false, - } -} - -func (cr *CRCommands) dockerLogin() error { - credentials, err := cr.Conf.AwsConfigure.GetECRCredentials(cr.Conf.AWSECRRegion) - if err != nil { - return err - } - - if token, ok := credentials[cr.Conf.AWSECRUserName]; !ok { - return fmt.Errorf("failed to get ECR token") - } else { - if cr.Ctx.Bool("get-token") { - fmt.Println(token) - return nil - } - - cr.SpecCMD = cr.docker("login", "--username", cr.Conf.AWSECRUserName, "--password", token, - cr.Conf.AWSECRHost) - if err := runner(cr).runCMD(); err != nil { - return err - } - - if !strings.Contains(cr.SpecCMD.StderrBuf.String(), "Using --password") { - return fmt.Errorf(strings.ReplaceAll(cr.SpecCMD.StderrBuf.String(), "\n", "")) - } - - zap.S().Info(strings.ReplaceAll(cr.SpecCMD.StdoutBuf.String(), "\n", "")) - } - - return nil -} - -func (cr *CRCommands) dockerLogout() error { - cr.SpecCMD = cr.docker("logout", cr.Conf.AWSECRHost) - if err := runner(cr).runCMD(); err != nil { - return err - } - - zap.S().Info(strings.ReplaceAll(cr.SpecCMD.StdoutBuf.String(), "\n", "")) - - return nil -} - -func containerRegistryAction(conf *config.Config, action func(dockerRunner DockerRunner) error) cli.ActionFunc { - return func(c *cli.Context) error { - if err := util.ValidateGitHubToken(c, ""); err != nil { - return err - } - - if err := util.ValidateNArg(c, 0); err != nil { - return err - } - - return action(newCRCommands(conf, c, util.GetPwdPath(""))) - } -} diff --git a/cmd/flags.go b/cmd/flags.go index a02b758..a1f7a4c 100644 --- a/cmd/flags.go +++ b/cmd/flags.go @@ -9,36 +9,6 @@ import ( func flagsConfig() []cli.Flag { return []cli.Flag{ - // TODO: will be transfer to cluster category for AWS provider - altsrc.NewStringFlag( - &cli.StringFlag{ - Name: "aws-ecr-host", - Usage: "AWS ECR host", - Aliases: []string{"aeh"}, - EnvVars: []string{"RMK_AWS_ECR_HOST"}, - Value: util.AWSECRHost, - }, - ), - // TODO: will be transfer to cluster category for AWS provider - altsrc.NewStringFlag( - &cli.StringFlag{ - Name: "aws-ecr-region", - Usage: "AWS region for specific ECR host", - Aliases: []string{"aer"}, - EnvVars: []string{"RMK_AWS_ECR_REGION"}, - Value: util.AWSECRRegion, - }, - ), - // TODO: will be transfer to cluster category for AWS provider - altsrc.NewStringFlag( - &cli.StringFlag{ - Name: "aws-ecr-user-name", - Usage: "AWS ECR user name", - Aliases: []string{"aeun"}, - EnvVars: []string{"RMK_AWS_ECR_USER_NAME"}, - Value: util.AWSECRUserName, - }, - ), altsrc.NewStringFlag( &cli.StringFlag{ Name: "aws-mfa-profile", @@ -56,15 +26,6 @@ func flagsConfig() []cli.Flag { Usage: "force AWS profile creation", Aliases: []string{"r"}, }, - // TODO: will be transfer to cluster category for AWS provider - altsrc.NewBoolFlag( - &cli.BoolFlag{ - Name: "cluster-provisioner-state-locking", - Usage: "disable or enable cluster provisioner state locking", - Aliases: []string{"c"}, - Value: true, - }, - ), &cli.StringFlag{ Name: "config", Hidden: true, @@ -89,15 +50,6 @@ func flagsConfig() []cli.Flag { EnvVars: []string{"RMK_GITHUB_TOKEN"}, }, ), - // TODO: will be transfer to cluster category - altsrc.NewStringFlag( - &cli.StringFlag{ - Name: "cloudflare-token", - Usage: "Cloudflare API token for provision NS records", - Aliases: []string{"cft"}, - EnvVars: []string{"RMK_CLOUDFLARE_TOKEN"}, - }, - ), altsrc.NewStringFlag( &cli.StringFlag{ Name: "cluster-provider", @@ -192,36 +144,26 @@ func flagsClusterK3DImport() []cli.Flag { ) } -func flagsClusterCRLogin() []cli.Flag { - return append(flagsHidden(), - &cli.BoolFlag{ - Name: "get-token", - Usage: "get ECR token for authentication", - Aliases: []string{"g"}, - }, - ) -} +//func flagsClusterPlan() []cli.Flag { +// return append(flagsHidden(), +// &cli.BoolFlag{ +// Name: "plan", +// Usage: "creates an execution Terraform plan", +// Aliases: []string{"p"}, +// }, +// ) +//} -func flagsClusterPlan() []cli.Flag { - return append(flagsHidden(), - &cli.BoolFlag{ - Name: "plan", - Usage: "creates an execution Terraform plan", - Aliases: []string{"p"}, - }, - ) -} - -func flagsClusterStateDelete() []cli.Flag { - return append(flagsHidden(), - &cli.StringFlag{ - Name: "resource-address", - Usage: "resource address for delete from Terraform state", - Aliases: []string{"ra"}, - EnvVars: []string{"RMK_CLUSTER_STATE_RESOURCE_ADDRESS"}, - }, - ) -} +//func flagsClusterStateDelete() []cli.Flag { +// return append(flagsHidden(), +// &cli.StringFlag{ +// Name: "resource-address", +// Usage: "resource address for delete from Terraform state", +// Aliases: []string{"ra"}, +// EnvVars: []string{"RMK_CLUSTER_STATE_RESOURCE_ADDRESS"}, +// }, +// ) +//} func flagsClusterSwitch() []cli.Flag { return append(flagsHidden(), @@ -428,12 +370,6 @@ func flagsHidden() []cli.Flag { Hidden: true, }, ), - altsrc.NewStringFlag( - &cli.StringFlag{ - Name: "cloudflare-token", - Hidden: true, - }, - ), altsrc.NewStringFlag( &cli.StringFlag{ Name: "cluster-provider", diff --git a/cmd/k3d.go b/cmd/k3d.go index 9dfc454..f7e9528 100644 --- a/cmd/k3d.go +++ b/cmd/k3d.go @@ -1,10 +1,7 @@ package cmd import ( - "fmt" "os" - "path/filepath" - "strings" "github.com/urfave/cli/v2" @@ -41,17 +38,12 @@ func (k *K3DCommands) k3d(args ...string) *util.SpecCMD { func (k *K3DCommands) prepareK3D(args ...string) error { k.SpecCMD = k.k3d(args...) k.SpecCMD.Debug = true - credentials, err := k.Conf.AwsConfigure.GetECRCredentials(k.Conf.AWSECRRegion) - if err != nil { - return err - } - k.SpecCMD.Envs = append(k.SpecCMD.Envs, "K3D_NAME="+k.Conf.Name) - - if token, ok := credentials[k.Conf.AWSECRUserName]; !ok { - return fmt.Errorf("failed to get ECR token") - } else { - k.SpecCMD.Envs = append(k.SpecCMD.Envs, "K3D_AWS_ECR_USER="+k.Conf.AWSECRUserName, "K3D_AWS_ECR_PASSWORD="+token) + switch { + case k.APICluster: + k.SpecCMD.Envs = append(k.SpecCMD.Envs, "K3D_NAME=capi") + case k.K3DCluster: + k.SpecCMD.Envs = append(k.SpecCMD.Envs, "K3D_NAME="+k.Conf.Name) } if len(k.Ctx.String("k3d-volume-host-path")) > 0 { @@ -65,50 +57,37 @@ func (k *K3DCommands) prepareK3D(args ...string) error { } func (k *K3DCommands) createDeleteK3DCluster() error { - var k3dDst string + switch k.Ctx.Command.Category { + case "capi": + k.APICluster = true + case "k3d": + k.K3DCluster = true + } - k.K3DCluster = true if _, _, err := k.getKubeContext(); err != nil { return err } - for name, pkg := range k.Conf.Clusters { - if strings.HasPrefix(name, util.K3DConfigPrefix) { - k3dDst = pkg.DstPath - break - } - } - - if len(k3dDst) == 0 { - return fmt.Errorf("cluster provider with name %s not found", util.K3DConfigPrefix) - } - - match, err := util.WalkMatch(k3dDst, util.K3DConfigPrefix+".yaml") - if err != nil { + k.SpecCMD = k.prepareHelmfile("-l", "app="+k.Ctx.Command.Category+"-cluster", "template") + k.SpecCMD.DisableStdOut = true + if err := runner(k).runCMD(); err != nil { return err } - if len(match) == 0 { - return fmt.Errorf("configuration file for %s not found", util.K3DConfigPrefix) - } - - if err := k.prepareK3D("cluster", k.Ctx.Command.Name, "--config", match[0]); err != nil { + k3dConfig, err := util.CreateTempYAMLFile("/tmp", k.Ctx.Command.Category+"-config", k.SpecCMD.StdoutBuf.Bytes()) + if err != nil { return err } - // Creating specific dir for k3d registry configuration - k3dRegistryHostPath := filepath.Join(filepath.Dir(match[0]), util.K3DConfigPrefix) - k.SpecCMD.Envs = append(k.SpecCMD.Envs, "K3D_REGISTRY_HOST_PATH="+k3dRegistryHostPath) - - if err := os.RemoveAll(k3dRegistryHostPath); err != nil { + if err := k.prepareK3D("cluster", k.Ctx.Command.Name, "--config", k3dConfig); err != nil { return err } - if err := os.MkdirAll(k3dRegistryHostPath, 0755); err != nil { + if err := runner(k).runCMD(); err != nil { return err } - return runner(k).runCMD() + return os.RemoveAll(k3dConfig) } func (k *K3DCommands) importImageToK3DCluster() error { @@ -156,7 +135,7 @@ func K3DCreateAction(conf *config.Config) cli.ActionFunc { return err } - if err := resolveDependencies(conf.InitConfig(false), c, false); err != nil { + if err := resolveDependencies(conf.InitConfig(), c, false); err != nil { return err } diff --git a/cmd/project.go b/cmd/project.go index 156f065..65f8829 100644 --- a/cmd/project.go +++ b/cmd/project.go @@ -419,7 +419,7 @@ func projectGenerateAction(conf *config.Config, gitSpec *git_handler.GitSpec) cl return err } - return resolveDependencies(conf.InitConfig(false), c, false) + return resolveDependencies(conf.InitConfig(), c, false) } } diff --git a/cmd/release.go b/cmd/release.go index 261ccec..245ad88 100644 --- a/cmd/release.go +++ b/cmd/release.go @@ -35,6 +35,7 @@ type ReleaseCommands struct { WorkDir string ValuesPath string UpdateContext bool + APICluster bool K3DCluster bool } @@ -173,31 +174,22 @@ func (rc *ReleaseCommands) prepareHelmfile(args ...string) *util.SpecCMD { "AWS_PROFILE="+rc.Conf.Profile, "AWS_CONFIG_FILE="+strings.Join(rc.Conf.AWSSharedConfigFile(rc.Conf.Profile), ""), "AWS_SHARED_CREDENTIALS_FILE="+strings.Join(rc.Conf.AWSSharedCredentialsFile(rc.Conf.Profile), ""), - // Needed to set the AWS region to force the connection session region for the helm S3 plugin, - // if AWS_DEFAULT_REGION and AWS_REGION cannot be trusted. - //"HELM_S3_REGION="+rc.Conf.S3ChartsRepoRegion, ) - if _, ok := rc.Conf.Env["ROOT_DOMAIN"]; ok { - envs = append(envs, "ROOT_DOMAIN="+rc.Conf.Env["ROOT_DOMAIN"]) - delete(rc.Conf.Env, "ROOT_DOMAIN") - } else { - envs = append(envs, "ROOT_DOMAIN="+rc.Conf.RootDomain) - } + envs = append(envs, "ROOT_DOMAIN="+rc.Conf.RootDomain) for _, val := range rc.Conf.HooksMapping { keyTenantEnv := regexp.MustCompile(`[\-.]`).ReplaceAllString(val.Tenant, "_") envs = append(envs, "HELMFILE_"+strings.ToUpper(keyTenantEnv)+"_HOOKS_DIR="+val.DstPath) } - for key, val := range rc.Conf.Env { - envs = append(envs, key+"="+val) - } - // generating additional environment variables to nested helmfiles envs = rc.nestedHelmfiles(envs...) - if rc.K3DCluster { + switch { + case rc.APICluster: + envs = append(envs, "CAPI_CLUSTER="+strconv.FormatBool(rc.APICluster)) + case rc.K3DCluster: envs = append(envs, "K3D_CLUSTER="+strconv.FormatBool(rc.K3DCluster)) } @@ -324,13 +316,13 @@ func (rc *ReleaseCommands) releaseKubeContext() error { return fmt.Errorf("current context %s already used for K3D cluster, --force flag cannot be used", contextName) } - cc := &ClusterCommands{ - Conf: rc.Conf, - Ctx: rc.Ctx, - WorkDir: util.GetPwdPath(""), - } + //cc := &ClusterCommands{ + // Conf: rc.Conf, + // Ctx: rc.Ctx, + // WorkDir: util.GetPwdPath(""), + //} - if err := cc.clusterContext(); err != nil { + if err := newClusterCommands(rc.Conf, rc.Ctx, util.GetPwdPath("")).awsClusterContext(); err != nil { return err } @@ -342,8 +334,8 @@ func (rc *ReleaseCommands) releaseKubeContext() error { rc.SpecCMD = rc.kubeConfig() rc.SpecCMD.Args = append(rc.SpecCMD.Args, "set-credentials", currentContext, - "--exec-env", "AWS_CONFIG_FILE="+strings.Join(rc.Conf.AWSSharedConfigFile(cc.Conf.Profile), ""), - "--exec-env", "AWS_SHARED_CREDENTIALS_FILE="+strings.Join(rc.Conf.AWSSharedCredentialsFile(cc.Conf.Profile), ""), + "--exec-env", "AWS_CONFIG_FILE="+strings.Join(rc.Conf.AWSSharedConfigFile(rc.Conf.Profile), ""), + "--exec-env", "AWS_SHARED_CREDENTIALS_FILE="+strings.Join(rc.Conf.AWSSharedCredentialsFile(rc.Conf.Profile), ""), ) rc.SpecCMD.DisableStdOut = true rc.SpecCMD.Debug = true @@ -652,7 +644,7 @@ func releaseHelmfileAction(conf *config.Config) cli.ActionFunc { return err } - if err := resolveDependencies(conf.InitConfig(false), c, false); err != nil { + if err := resolveDependencies(conf.InitConfig(), c, false); err != nil { return err } @@ -705,7 +697,7 @@ func releaseRollbackAction(conf *config.Config) cli.ActionFunc { return err } - if err := resolveDependencies(conf.InitConfig(false), c, false); err != nil { + if err := resolveDependencies(conf.InitConfig(), c, false); err != nil { return err } @@ -742,7 +734,7 @@ func releaseUpdateAction(conf *config.Config, gitSpec *git_handler.GitSpec) cli. return err } - if err := resolveDependencies(conf.InitConfig(false), c, false); err != nil { + if err := resolveDependencies(conf.InitConfig(), c, false); err != nil { return err } diff --git a/cmd/secret.go b/cmd/secret.go index e25bc97..93c9ec1 100644 --- a/cmd/secret.go +++ b/cmd/secret.go @@ -387,7 +387,7 @@ func secretMgrEncryptDecryptAction(conf *config.Config) cli.ActionFunc { return err } - if err := resolveDependencies(conf.InitConfig(false), c, false); err != nil { + if err := resolveDependencies(conf.InitConfig(), c, false); err != nil { return err } @@ -414,7 +414,7 @@ func secretKeysCreateAction(conf *config.Config) cli.ActionFunc { return err } - if err := resolveDependencies(conf.InitConfig(false), c, false); err != nil { + if err := resolveDependencies(conf.InitConfig(), c, false); err != nil { return err } @@ -452,7 +452,7 @@ func secretAction(conf *config.Config, action func(secretRunner SecretRunner) er return err } - if err := resolveDependencies(conf.InitConfig(false), c, false); err != nil { + if err := resolveDependencies(conf.InitConfig(), c, false); err != nil { return err } diff --git a/config/config.go b/config/config.go index 800c8cc..07cea85 100644 --- a/config/config.go +++ b/config/config.go @@ -6,10 +6,8 @@ import ( "fmt" "os" "path/filepath" - "reflect" "regexp" "runtime" - "strconv" "strings" "text/template" @@ -29,7 +27,6 @@ type Config struct { Environment string `yaml:"environment,omitempty"` ConfigNameFrom string `yaml:"config-name-from,omitempty"` RootDomain string `yaml:"root-domain,omitempty"` - CloudflareToken string `yaml:"cloudflare-token,omitempty"` GitHubToken string `yaml:"github-token,omitempty"` ClusterProvider string `yaml:"cluster-provider"` SlackNotifications bool `yaml:"slack-notifications"` @@ -38,15 +35,9 @@ type Config struct { SlackMsgDetails []string `yaml:"slack-message-details,omitempty"` SopsAgeKeys string `yaml:"sops-age-keys,omitempty"` SopsBucketName string `yaml:"sops-bucket-name,omitempty"` - AWSECRHost string `yaml:"aws-ecr-host,omitempty"` - AWSECRRegion string `yaml:"aws-ecr-region,omitempty"` - AWSECRUserName string `yaml:"aws-ecr-user-name,omitempty"` AWSMFAProfile string `yaml:"aws-mfa-profile,omitempty"` AWSMFATokenExpiration string `yaml:"aws-mfa-token-expiration,omitempty"` *aws_provider.AwsConfigure `yaml:"aws,omitempty"` - Terraform `yaml:"terraform,omitempty"` - ClusterProvisionerSL bool `yaml:"cluster-provisioner-state-locking"` - ExportedVars `yaml:"exported-vars,omitempty"` ProgressBar bool `yaml:"progress-bar"` ProjectFile `yaml:"project-file"` } @@ -106,25 +97,12 @@ type Terraform struct { DDBTableName string `yaml:"dynamodb-table-name,omitempty"` } -func (conf *Config) InitConfig(terraformOutput bool) *Config { +func (conf *Config) InitConfig() *Config { conf.ProjectFile = ProjectFile{} if err := conf.ReadProjectFile(util.GetPwdPath(util.TenantProjectFile)); err != nil { zap.S().Fatal(err) } - if !terraformOutput { - return conf - } - - conf.ExportedVars = ExportedVars{ - TerraformOutput: make(map[string]interface{}), - Env: make(map[string]string), - } - - if err := conf.GetTerraformOutputs(); err != nil { - zap.S().Fatal(err) - } - return conf } @@ -187,16 +165,9 @@ func (conf *Config) GetConfigs(all bool) error { } func (conf *Config) SetRootDomain(c *cli.Context, gitSpecID string) error { - hostedZoneVar := util.TerraformVarsPrefix + util.TerraformVarHostedZoneName if !c.IsSet("root-domain") { - if hostedZoneName, ok := conf.TerraformOutput[hostedZoneVar]; ok && len(hostedZoneName.(string)) > 0 { - if err := c.Set("root-domain", hostedZoneName.(string)); err != nil { - return err - } - } else { - if err := c.Set("root-domain", gitSpecID+util.TenantDomainSuffix); err != nil { - return err - } + if err := c.Set("root-domain", gitSpecID+util.TenantDomainSuffix); err != nil { + return err } } @@ -205,69 +176,6 @@ func (conf *Config) SetRootDomain(c *cli.Context, gitSpecID string) error { return nil } -func (conf *Config) GetTerraformOutputs() error { - type GetVar struct { - Type interface{} - Value interface{} - } - - var ( - raw map[string]*json.RawMessage - outputs map[string]*json.RawMessage - getVar *GetVar - ) - - checkWorkspace, err := conf.BucketKeyExists("", conf.Terraform.BucketName, "env:/"+conf.Name+"/tf.tfstate") - if err != nil { - return err - } - - if !checkWorkspace { - return nil - } - - data, err := conf.GetFileData(conf.Terraform.BucketName, "env:/"+conf.Name+"/tf.tfstate") - if err != nil { - return err - } - - if err := json.Unmarshal(data, &raw); err != nil { - return err - } - - if err := json.Unmarshal(*raw["outputs"], &outputs); err != nil { - return err - } - - if len(outputs) == 0 { - return nil - } - - for key := range outputs { - if strings.Contains(key, util.TerraformVarsPrefix) { - if err := json.Unmarshal(*outputs[key], &getVar); err != nil { - return err - } - - envKey := strings.ToUpper(strings.ReplaceAll(key, util.TerraformVarsPrefix, "")) - - switch { - case reflect.TypeOf(getVar.Value).Kind() == reflect.String && getVar.Type == reflect.String.String(): - conf.TerraformOutput[key] = getVar.Value - conf.Env[envKey] = getVar.Value.(string) - case reflect.TypeOf(getVar.Value).Kind() == reflect.Bool && getVar.Type == reflect.Bool.String(): - conf.TerraformOutput[key] = getVar.Value - conf.Env[envKey] = strconv.FormatBool(getVar.Value.(bool)) - default: - zap.S().Warnf("Terraform output variable %s will not be exported as environment variable, "+ - "does not match string or boolean types, current type: %s", key, getVar.Type) - } - } - } - - return nil -} - func (pf *ProjectFile) ReadProjectFile(path string) error { data, err := os.ReadFile(path) if err != nil { diff --git a/util/dictionary.go b/util/dictionary.go index 6b29a1b..baf086a 100644 --- a/util/dictionary.go +++ b/util/dictionary.go @@ -1,50 +1,42 @@ package util const ( - AWSClusterProvider = "aws" - AzureClusterProvider = "azure" - AWSECRHost = "288509344804.dkr.ecr.eu-north-1.amazonaws.com" - AWSECRRegion = "eu-north-1" - AWSECRUserName = "AWS" - GitSSHPrivateKey = ".ssh/id_rsa" - GlobalsFileName = "globals.yaml.gotmpl" - HelmfileFileName = "helmfile.yaml" - HelmfileGoTmplName = HelmfileFileName + ".gotmpl" - HelpFlagFull = "--help" - K3DConfigPrefix = "k3d" - LocalClusterProvider = K3DConfigPrefix - RMKBin = "rmk" - RMKBucketName = "edenlabllc-rmk" - RMKBucketRegion = "eu-north-1" - RMKConfig = "config" - RMKDir = ".rmk" - RMKSymLinkPath = "/usr/local/bin/rmk" - RMKToolsDir = "tools" - ReadmeFileName = "README.md" - RegionException = "us-east-1" - ReleasesFileName = "releases.yaml" - SecretSpecFile = ".spec.yaml.gotmpl" - SopsAgeKeyExt = ".txt" - SopsAgeKeyFile = ".keys.txt" - SopsRootName = "sops-age-keys" - SopsConfigFile = ".sops.yaml" - TenantBucketKey = "tf.tfstate" - TenantBucketName = "cloud-provisioner" - TenantDDBTablePrefix = "cloud-provisioner-state-locks" - TenantDomainSuffix = ".edenlab.dev" - TenantProjectCodeOwners = "docs/CODEOWNERS" - TenantProjectDIR = ".PROJECT" - TenantProjectFile = "project.yaml" - TenantProjectGitIgn = ".gitignore" - TenantValuesDIR = "etc" - TerraformVarHostedZoneName = "hosted_zone_name" - TerraformVarsExt = "tfvars" - TerraformVarsFile = "variables.auto." + TerraformVarsExt - TerraformVarsPrefix = "rmk_" - TerraformWGFile = "worker-groups.auto." + TerraformVarsExt - ToolsBinDir = "bin" - ToolsTmpDir = "tmp" - ToolsVersionDir = "version" + AWSClusterProvider = "aws" + AzureClusterProvider = "azure" + GitSSHPrivateKey = ".ssh/id_rsa" + GlobalsFileName = "globals.yaml.gotmpl" + HelmfileFileName = "helmfile.yaml" + HelmfileGoTmplName = HelmfileFileName + ".gotmpl" + HelpFlagFull = "--help" + K3DConfigPrefix = "k3d" + LocalClusterProvider = K3DConfigPrefix + RMKBin = "rmk" + RMKBucketName = "edenlabllc-rmk" + RMKBucketRegion = "eu-north-1" + RMKConfig = "config" + RMKDir = ".rmk" + RMKSymLinkPath = "/usr/local/bin/rmk" + RMKToolsDir = "tools" + ReadmeFileName = "README.md" + RegionException = "us-east-1" + ReleasesFileName = "releases.yaml" + SecretSpecFile = ".spec.yaml.gotmpl" + SopsAgeKeyExt = ".txt" + SopsAgeKeyFile = ".keys.txt" + SopsRootName = "sops-age-keys" + SopsConfigFile = ".sops.yaml" + TenantDomainSuffix = ".edenlab.dev" + TenantProjectCodeOwners = "docs/CODEOWNERS" + TenantProjectDIR = ".PROJECT" + TenantProjectFile = "project.yaml" + TenantProjectGitIgn = ".gitignore" + TenantValuesDIR = "etc" + TerraformVarsExt = "tfvars" + TerraformVarsFile = "variables.auto." + TerraformVarsExt + TerraformWGFile = "worker-groups.auto." + TerraformVarsExt + ToolsBinDir = "bin" + ToolsTmpDir = "tmp" + ToolsVersionDir = "version" ConfigNotInitializedErrorText = "RMK config not initialized, " + "please run command 'rmk config init' with specific parameters" diff --git a/util/system.go b/util/system.go index 67301e6..afa599c 100644 --- a/util/system.go +++ b/util/system.go @@ -397,3 +397,18 @@ func UnTar(dst, excludeRegexp string, r io.Reader) error { } } } + +func CreateTempYAMLFile(dirPath, fileName string, content []byte) (string, error) { + file, err := os.CreateTemp(dirPath, fileName+".*.yaml") + if err != nil { + return "", err + } + + if _, err := file.Write(content); err != nil { + return "", err + } + + defer file.Close() + + return file.Name(), nil +}