Skip to content

Commit

Permalink
Modify module to make it 'go get-able'
Browse files Browse the repository at this point in the history
  • Loading branch information
elidhu committed Sep 19, 2020
1 parent 81e6464 commit 10efb1a
Show file tree
Hide file tree
Showing 9 changed files with 214 additions and 261 deletions.
1 change: 0 additions & 1 deletion cmd/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ var (
Use: "delete",
Short: "Delete parameters from SSM",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("delete called")
deleteParameters(&names)
},
}
Expand Down
134 changes: 134 additions & 0 deletions cmd/env.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/*
The MIT License (MIT)
Copyright (c) 2020 Kevin Glasson
Copyright (c) 2015 99designs (substantial copy of 'aws-vault exec')
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package cmd

import (
"fmt"

"github.com/spf13/cobra"
)

// envCmd represents the env command
var envCmd = &cobra.Command{
Use: "env",
Short: "A brief description of your command",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("env called")
},
}

func init() {
// rootCmd.AddCommand(envCmd)

// Here you will define your flags and configuration settings.

// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// envCmd.PersistentFlags().String("foo", "", "A help for foo")

// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// envCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

// func execEnvironment(input ExecCommandInput, config *vault.Config, creds *credentials.Credentials) error {
// val, err := creds.Get()
// if err != nil {
// return fmt.Errorf("Failed to get credentials for %s: %w", input.ProfileName, err)
// }

// env := environ(os.Environ())
// env = updateEnvForAwsVault(env, input.ProfileName, config.Region)

// log.Println("Setting subprocess env: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY")
// env.Set("AWS_ACCESS_KEY_ID", val.AccessKeyID)
// env.Set("AWS_SECRET_ACCESS_KEY", val.SecretAccessKey)

// if val.SessionToken != "" {
// log.Println("Setting subprocess env: AWS_SESSION_TOKEN, AWS_SECURITY_TOKEN")
// env.Set("AWS_SESSION_TOKEN", val.SessionToken)
// env.Set("AWS_SECURITY_TOKEN", val.SessionToken)
// }
// if expiration, err := creds.ExpiresAt(); err == nil {
// log.Println("Setting subprocess env: AWS_SESSION_EXPIRATION")
// env.Set("AWS_SESSION_EXPIRATION", iso8601.Format(expiration))
// }

// if !supportsExecSyscall() {
// return execCmd(input.Command, input.Args, env)
// }

// return execSyscall(input.Command, input.Args, env)
// }

// func execCmd(command string, args []string, env []string) error {
// log.Printf("Starting child process: %s %s", command, strings.Join(args, " "))

// cmd := exec.Command(command, args...)
// cmd.Stdin = os.Stdin
// cmd.Stdout = os.Stdout
// cmd.Stderr = os.Stderr
// cmd.Env = env

// sigChan := make(chan os.Signal, 1)
// signal.Notify(sigChan)

// if err := cmd.Start(); err != nil {
// return err
// }

// go func() {
// for {
// sig := <-sigChan
// cmd.Process.Signal(sig)
// }
// }()

// if err := cmd.Wait(); err != nil {
// cmd.Process.Signal(os.Kill)
// return fmt.Errorf("Failed to wait for command termination: %v", err)
// }

// waitStatus := cmd.ProcessState.Sys().(syscall.WaitStatus)
// os.Exit(waitStatus.ExitStatus())
// return nil
// }

// func execSyscall(command string, args []string, env []string) error {
// log.Printf("Exec command %s %s", command, strings.Join(args, " "))

// argv0, err := exec.LookPath(command)
// if err != nil {
// return fmt.Errorf("Couldn't find the executable '%s': %w", command, err)
// }

// log.Printf("Found executable %s", argv0)

// argv := make([]string, 0, 1+len(args))
// argv = append(argv, command)
// argv = append(argv, args...)

// return syscall.Exec(argv0, argv, env)
// }
13 changes: 9 additions & 4 deletions cmd/import.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ package cmd

import (
"fmt"
"goss/internal/utils"

"github.com/kevinglasson/goss/internal/utils"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
Expand All @@ -16,14 +17,15 @@ var (
// For flags
file string
importType string
importPath string
importOWrite bool

// importCmd represents the import command
importCmd = &cobra.Command{
Use: "import",
Short: "Import a file into SSM at the given path",
Run: func(cmd *cobra.Command, args []string) {
err := importParameters(file, importType, importOWrite)
err := importParameters(file, importType, importPath, importOWrite)
if err != nil {
utils.PrintErrorAndExit(err)
}
Expand All @@ -41,13 +43,16 @@ func init() {
importCmd.Flags().StringVarP(
&importType, "type", "t", "", "type of the parameter",
)
importCmd.Flags().StringVarP(
&importPath, "path", "p", "", "path to prefix parameters",
)
importCmd.MarkFlagRequired("type")
importCmd.Flags().BoolVarP(
&importOWrite, "overwrite", "o", false, "overwrite parameters if they exist",
)
}

func importParameters(file string, typ string, overwrite bool) error {
func importParameters(file string, typ string, path string, overwrite bool) error {

provider := kfile.Provider(file)
parser := kdotenv.Parser()
Expand Down Expand Up @@ -80,7 +85,7 @@ func importParameters(file string, typ string, overwrite bool) error {
// Retrieve parameters
_, err = svc.PutParameter(
&ssm.PutParameterInput{
Name: aws.String(k),
Name: aws.String(fmt.Sprintf("%s/%s", path, k)),
Value: aws.String(v.(string)),
Type: aws.String(typ),
Overwrite: aws.Bool(overwrite),
Expand Down
29 changes: 19 additions & 10 deletions cmd/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ package cmd
import (
"encoding/json"
"fmt"
"goss/internal/utils"
"os"
"strconv"
"time"

"github.com/kevinglasson/goss/internal/utils"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
Expand All @@ -16,18 +19,14 @@ import (
// listCmd represents the list command.
var (
// For flags.
path string
recursive bool
decrypt bool

listCmd = &cobra.Command{
Use: "list PATH",
Short: "List parameters in SSM by path",
Args: cobra.ExactArgs(1),
ValidArgs: []string{"path"},
Use: "list",
Short: "List parameters SSM",
Run: func(cmd *cobra.Command, args []string) {
// Guaranteed to work because of ExactArgs.
path := args[0]

// Global flags.
asJSON, err := cmd.Flags().GetBool("json")
if err != nil {
Expand All @@ -46,7 +45,13 @@ var (
func init() {
rootCmd.AddCommand(listCmd)

listCmd.Flags().BoolVarP(&recursive, "recursive", "r", false, "recurse into parameter path")
listCmd.Flags().StringVarP(
&path, "path", "p", "", "parameter(s) path",
)
listCmd.MarkFlagRequired("path")
listCmd.Flags().BoolVarP(
&recursive, "recursive", "r", false, "recurse into parameter path",
)
listCmd.Flags().BoolVarP(&decrypt, "decrypt", "d", false, "decrypt values")
}

Expand Down Expand Up @@ -86,13 +91,17 @@ func listParameters(
fmt.Println(string(out))
} else {
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Name", "Value"})
table.SetHeader([]string{"Name", "Value", "Version", "Last Mod"})

for _, v := range res.Parameters {
table.Append(
[]string{
utils.TruncateString(*v.Name, 35),
utils.TruncateString(*v.Value, 35),
utils.TruncateString(strconv.FormatInt(*v.Version, 10), 35),
utils.TruncateString(
v.LastModifiedDate.Format(time.RFC3339), 35,
),
},
)
}
Expand Down
11 changes: 6 additions & 5 deletions cmd/put.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ package cmd

import (
"fmt"
"goss/internal/utils"

"github.com/kevinglasson/goss/internal/utils"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
Expand All @@ -19,7 +20,7 @@ var (

putCmd = &cobra.Command{
Use: "put",
Short: "Put a parameter (or a file of them) into SSM",
Short: "Put a single parameter into SSM",
Run: func(cmd *cobra.Command, args []string) {

// Run and report errors.
Expand All @@ -34,11 +35,11 @@ var (
func init() {
rootCmd.AddCommand(putCmd)

putCmd.Flags().StringVarP(&name, "name", "n", "", "full path name of the parameter")
putCmd.Flags().StringVarP(&name, "name", "n", "", "parameter name including path")
putCmd.MarkFlagRequired("name")
putCmd.Flags().StringVarP(&value, "value", "v", "", "value of the parameter")
putCmd.Flags().StringVarP(&value, "value", "v", "", "parameter value")
putCmd.MarkFlagRequired("value")
putCmd.Flags().StringVarP(&putType, "type", "t", "", "type of the parameter")
putCmd.Flags().StringVarP(&putType, "type", "t", "", "parameter type")
putCmd.MarkFlagRequired("type")
putCmd.Flags().BoolVarP(
&putOWrite, "overwrite", "o", false, "overwrite parameter if it exists",
Expand Down
65 changes: 31 additions & 34 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
//Package cmd contains all of the commands for the goss CLI tool.
package cmd

import (
"fmt"
"os"

"github.com/spf13/cobra"

homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/viper"
)

var (
Expand All @@ -19,12 +17,16 @@ var (
// rootCmd represents the base command when called without any subcommands
rootCmd = &cobra.Command{
Use: "goss",
Short: "AWS SSM paramter store manager",
Long: `For importing and exporting secrets to AWS SSM from a local file for
use in AWS applications
Short: "goss in an AWS SSM Paramter Store manager",
Long: `goss is used to interact with the AWS SSM Parameter Store in a
variety of helpful ways.
You can interact in bulk through the 'import' sub-command to import parameters
directly from a local file.
Inspired by another cli tool 'chamber' but with AWS SSM support only. This is to
facillitate syncing path based secrets from TOML files to AWS SSM.`,
You can also interact with paths individually to list, put and delete
parameters.
`,
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
Expand All @@ -42,38 +44,33 @@ func Execute() {

func init() {
cobra.OnInitialize(initConfig)

// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.

rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.goss.toml)")
// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.goss.toml)")
rootCmd.PersistentFlags().BoolVar(&asJSON, "json", false, "output as json")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// if cfgFile != "" {
// // Use config file from the flag.
// viper.SetConfigFile(cfgFile)
// } else {
// // Find home directory.
// home, err := homedir.Dir()
// if err != nil {
// fmt.Println(err)
// os.Exit(1)
// }

// Search config in home directory with name ".goss" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".goss")
viper.SetConfigType("toml")
}
// // Search config in home directory with name ".goss" (without extension).
// viper.AddConfigPath(home)
// viper.SetConfigName(".goss")
// viper.SetConfigType("toml")
// }

viper.AutomaticEnv() // read in environment variables that match
// viper.AutomaticEnv() // read in environment variables that match

// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
// // If a config file is found, read it in.
// if err := viper.ReadInConfig(); err == nil {
// fmt.Println("Using config file:", viper.ConfigFileUsed())
// }
}
Loading

0 comments on commit 10efb1a

Please sign in to comment.