Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TOOLS-28 add config set command #5

Merged
merged 2 commits into from
Oct 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions internal/commands/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,11 @@ func (b *commandsBuilder) addCommands(commands ...cmder) *commandsBuilder {
}

func (b *commandsBuilder) addAll() *commandsBuilder {
b.addCommands(b.newTerraformCmd())
b.addCommands(
b.newTerraformCmd(),
b.newConfigCmd(),
b.newEnvCmd(),
)

return b
}
Expand All @@ -74,7 +78,7 @@ to quickly create a Cobra application.`,

cc.cmd.SilenceErrors = true
cc.cmd.SilenceUsage = true
cc.cmd.PersistentFlags().StringVarP(&cc.ll, "log-level", "l", "", "enable debug message")
cc.cmd.PersistentFlags().StringVarP(&cc.ll, "log-level", "l", "infa", "enable debug message")
cc.cmd.PersistentFlags().StringVarP(&cc.cfgFile, "config-file", "c", "", "set config file name")

var logLevel zapcore.Level
Expand Down
144 changes: 144 additions & 0 deletions internal/commands/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
package commands

import (
"encoding/json"
"fmt"
"io/ioutil"
"os"

"github.com/hazelops/ize/internal/aws/utils"
"github.com/pterm/pterm"
"github.com/spf13/cobra"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ssm"
)

type configCmd struct {
*baseBuilderCmd

vaultType string
filePath string
}

func (b *commandsBuilder) newConfigCmd() *configCmd {
cc := &configCmd{}

cmd := &cobra.Command{
Use: "config",
Short: "",
Long: "",
RunE: nil,
TraverseChildren: true,
}

setCmd := &cobra.Command{
Use: "set",
Short: "Set secrets to storage",
Long: "This command set sercrets to storage",
RunE: func(cmd *cobra.Command, args []string) error {
err := cc.Init()
if err != nil {
return err
}

pterm.DefaultSection.Printfln("Starting config setting")

if cc.vaultType == "ssm" {
err = Set(cc.config.AwsRegion, cc.filePath, fmt.Sprintf("/%s/%s", cc.config.Env, cc.config.Namespace))
if err != nil {
pterm.DefaultSection.Println("Config setting not completed")
return err
}
} else {
pterm.DefaultSection.Println("Config setting not completed")
return fmt.Errorf("vault with type %s not found or not supported", cc.vaultType)
}

pterm.DefaultSection.Printfln("Config setting completed")

return nil
},
}

setCmd.Flags().StringVar(&cc.vaultType, "type", "", "vault type")
setCmd.Flags().StringVar(&cc.filePath, "file", "", "file with sercrets")

cmd.AddCommand(setCmd)

cc.baseBuilderCmd = b.newBuilderBasicCdm(cmd)

return cc
}

func Set(region string, file string, path string) error {
sess, err := utils.GetSession(&utils.SessionConfig{
Region: region,
})
if err != nil {
return err
}

pterm.Success.Printfln("Geting AWS session")

values, err := getKeyValuePairs(file)
if err != nil {
return err
}

pterm.Success.Printfln("Reading secrets from file")

ssmSvc := ssm.New(sess)

for key, value := range values {
name := fmt.Sprintf("%s/%s", path, key)

_, err := ssmSvc.PutParameter(&ssm.PutParameterInput{
Name: &name,
Value: aws.String(value),
Type: aws.String(ssm.ParameterTypeSecureString),
Tags: []*ssm.Tag{
{
Key: aws.String("EnvVarName"),
Value: &key,
},
},
})

if err != nil {
return err
}
}

pterm.Success.Printfln("Putting secrets in SSM")

return err
}

func getKeyValuePairs(file string) (map[string]string, error) {
wd, err := os.Getwd()
if err != nil {
return nil, err
}

f, err := os.Open(wd + "/" + file)
if err != nil {
return nil, err
}

defer f.Close()

bytes, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}

var result map[string]string

err = json.Unmarshal(bytes, &result)
if err != nil {
return nil, err
}

return result, nil
}
127 changes: 127 additions & 0 deletions internal/commands/env.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
package commands

import (
"fmt"
"io/ioutil"

"github.com/aws/aws-sdk-go/service/sts"
"github.com/hazelops/ize/internal/aws/utils"
"github.com/hazelops/ize/internal/template"
"github.com/pterm/pterm"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

type envCmd struct {
*baseBuilderCmd
}

func (b *commandsBuilder) newEnvCmd() *envCmd {
cc := &envCmd{}

cmd := &cobra.Command{
Use: "env",
Short: "",
Long: "",
RunE: nil,
TraverseChildren: true,
}

envCmd := &cobra.Command{
Use: "terraform",
Short: "Generate terraform files",
Long: "This command generate terraform files",
RunE: func(cmd *cobra.Command, args []string) error {
err := cc.Init()
if err != nil {
return err
}

pterm.DefaultSection.Printfln("Starting generate terrafrom files")

err = template.GenereateBackendTf(template.BackendOpts{
ENV: cc.config.Env,
LOCALSTACK_ENDPOINT: "",
TERRAFORM_STATE_BUCKET_NAME: fmt.Sprintf("%s-tf-state", cc.config.Namespace),
TERRAFORM_STATE_KEY: fmt.Sprintf("%v/terraform.tfstate", cc.config.Env),
TERRAFORM_STATE_REGION: cc.config.AwsRegion,
TERRAFORM_STATE_PROFILE: cc.config.AwsProfile,
TERRAFORM_STATE_DYNAMODB_TABLE: "tf-state-lock", // So? // TODO: cc.config.TERRAFORM_STATE_DYNAMODB_TABLE
TERRAFORM_AWS_PROVIDER_VERSION: "",
},
viper.GetString("ENV_DIR"),
)

if err != nil {
pterm.DefaultSection.Println("Generate terrafrom file not completed")
return err
}

pterm.Success.Println("backend.tf generated")

sess, err := utils.GetSession(&utils.SessionConfig{
Region: cc.config.AwsRegion,
})
if err != nil {
pterm.DefaultSection.Println("Generate terrafrom file not completed")
return err
}

pterm.Success.Printfln("Read SSH public key")
cc.log.Debug("Read SSH public key")

// TODO: FIX
key, err := ioutil.ReadFile("/home/psih/.ssh/id_rsa.pub")
if err != nil {
pterm.DefaultSection.Println("Generate terrafrom file not completed")
return err
}

stsSvc := sts.New(sess)

resp, err := stsSvc.GetCallerIdentity(
&sts.GetCallerIdentityInput{},
)

if err != nil {
pterm.DefaultSection.Println("Generate terrafrom file not completed")
return err
}

err = template.GenerateVarsTf(template.VarsOpts{
ENV: cc.config.Env,
AWS_PROFILE: cc.config.AwsProfile,
AWS_REGION: cc.config.AwsRegion,
EC2_KEY_PAIR_NAME: fmt.Sprintf("%v-%v", cc.config.Env, cc.config.Namespace),
TAG: cc.config.Env,
SSH_PUBLIC_KEY: string(key)[:len(string(key))-1],
DOCKER_REGISTRY: fmt.Sprintf("%v.dkr.ecr.%v.amazonaws.com", *resp.Account, cc.config.AwsRegion),
NAMESPACE: cc.config.Namespace,
},
viper.GetString("ENV_DIR"),
)

if err != nil {
pterm.DefaultSection.Println("Generate terrafrom file not completed")
return err
}

pterm.Success.Println("terraform.tfvars generated")

if err != nil {
pterm.DefaultSection.Println("Generate terrafrom file not completed")
return err
}

pterm.DefaultSection.Printfln("Generate terrafrom files completed")

return nil
},
}

cmd.AddCommand(envCmd)

cc.baseBuilderCmd = b.newBuilderBasicCdm(cmd)

return cc
}
70 changes: 2 additions & 68 deletions internal/commands/terraform.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,11 @@ import (
"io/ioutil"
"os"

"github.com/aws/aws-sdk-go/service/sts"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/hazelops/ize/internal/aws/utils"
"github.com/hazelops/ize/internal/template"
"github.com/moby/term"
"github.com/pterm/pterm"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -47,71 +44,6 @@ func (b *commandsBuilder) newTerraformCmd() *terraformCmd {

pterm.DefaultSection.Println("Generating terraform files")

err = template.GenereateBackendTf(template.BackendOpts{
ENV: cc.config.Env,
LOCALSTACK_ENDPOINT: "",
TERRAFORM_STATE_BUCKET_NAME: fmt.Sprintf("%s-tf-state", cc.config.Namespace),
TERRAFORM_STATE_KEY: fmt.Sprintf("%v/terraform.tfstate", cc.config.Env),
TERRAFORM_STATE_REGION: cc.config.AwsRegion,
TERRAFORM_STATE_PROFILE: cc.config.AwsProfile,
TERRAFORM_STATE_DYNAMODB_TABLE: "tf-state-lock", // So?
TERRAFORM_AWS_PROVIDER_VERSION: "",
},
viper.GetString("ENV_DIR"),
)

pterm.Success.Println("backend.tf generated")

if err != nil {
pterm.Error.Println("backend.tf not generated")
return err
}

sess, err := utils.GetSession(&utils.SessionConfig{
Region: cc.config.AwsRegion,
})
if err != nil {
return err
}

pterm.Success.Printfln("Read SSH public key")
cc.log.Debug("Read SSH public key")

key, err := ioutil.ReadFile("/home/psih/.ssh/id_rsa.pub")
if err != nil {
return err
}

stsSvc := sts.New(sess)

resp, err := stsSvc.GetCallerIdentity(
&sts.GetCallerIdentityInput{},
)

if err != nil {
return err
}

err = template.GenerateVarsTf(template.VarsOpts{
ENV: cc.config.Env,
AWS_PROFILE: cc.config.AwsProfile,
AWS_REGION: cc.config.AwsRegion,
EC2_KEY_PAIR_NAME: fmt.Sprintf("%v-%v", cc.config.Env, cc.config.Namespace),
TAG: cc.config.Env,
SSH_PUBLIC_KEY: string(key)[:len(string(key))-1],
DOCKER_REGISTRY: fmt.Sprintf("%v.dkr.ecr.%v.amazonaws.com", *resp.Account, cc.config.AwsRegion),
NAMESPACE: cc.config.Namespace,
},
viper.GetString("ENV_DIR"),
)

if err != nil {
pterm.Error.Println("terraform.tfvars not generated")
return err
}

pterm.Success.Println("terraform.tfvars generated")

opts := TerraformRunOption{
ContainerName: "terraform-init",
Cmd: []string{"init", "-input=true"},
Expand Down Expand Up @@ -263,6 +195,8 @@ func runTerraform(cc *terraformCmd, opts TerraformRunOption) error {
return err
}

cc.log.Debugf(fmt.Sprintf("%v", viper.Get("ENV_DIR")))

//TODO: Add Auto Pull Docker image
cont, err := cli.ContainerCreate(
context.Background(),
Expand Down