Skip to content

Commit

Permalink
Add expanding variables through /bin/sh when running a command
Browse files Browse the repository at this point in the history
  • Loading branch information
Eugene Dementiev committed Apr 17, 2018
1 parent 2a5ee93 commit 3b45767
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
4 changes: 2 additions & 2 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ var (

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "parent",
Use: "ssm-parent",
Short: "Docker entrypoint that get parameters from AWS SSM Parameter Store",
Long: `Parent is a docker entrypoint.
Long: `SSM-Parent is a docker entrypoint.
It gets specified parameters (possibly secret) from AWS SSM Parameter Store,
then exports them to the underlying process.
Expand Down
34 changes: 32 additions & 2 deletions cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"os"
"os/exec"
"os/signal"
"strings"

"github.com/springload/ssm-parent/ssm"

Expand All @@ -13,11 +14,16 @@ import (
"github.com/spf13/cobra"
)

var expand bool

// runCmd represents the run command
var runCmd = &cobra.Command{
Use: "run",
Use: "run command",
Short: "Runs the specified command",
Args: cobra.MinimumNArgs(1),
Run: func(cobraCmd *cobra.Command, args []string) {
var cmdArgs []string

megamap := make(map[string]interface{})
parameters, err := ssm.GetParameters(names, paths, strict, recursive)
if err != nil {
Expand All @@ -41,8 +47,13 @@ var runCmd = &cobra.Command{

c := make(chan os.Signal, 1)
signal.Notify(c)
if expand {
cmdArgs = expandArgs(args[1:])
} else {
cmdArgs = args[1:]
}

cmd := exec.Command(command, args[1:]...)
cmd := exec.Command(command, cmdArgs...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
Expand All @@ -64,6 +75,25 @@ var runCmd = &cobra.Command{
},
}

// expandArgs leverages on shell and echo to expand
// possible args mainly env vars.
// taken from https://github.com/abiosoft/parent
func expandArgs(args []string) []string {
var expanded []string
for _, arg := range args {
e, err := exec.Command("/bin/sh", "-c", fmt.Sprintf("echo %s", arg)).Output()
// error is not expected.
// in the rare case that this errors
// the original arg is still used.
if err == nil {
arg = strings.TrimSpace(string(e))
}
expanded = append(expanded, arg)
}
return expanded
}

func init() {
runCmd.Flags().BoolVarP(&expand, "expand", "e", false, "Expand arguments using /bin/sh")
rootCmd.AddCommand(runCmd)
}

0 comments on commit 3b45767

Please sign in to comment.