Skip to content

Commit

Permalink
feat: support passing variables via environment variables
Browse files Browse the repository at this point in the history
  • Loading branch information
suzuki-shunsuke committed Apr 18, 2023
1 parent 8d52a9b commit f2bef37
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
4 changes: 3 additions & 1 deletion pkg/cli/apply.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cli

import (
"os"

"github.com/suzuki-shunsuke/tfcmt/pkg/controller"
"github.com/suzuki-shunsuke/tfcmt/pkg/terraform"
"github.com/urfave/cli/v2"
Expand All @@ -20,7 +22,7 @@ func cmdApply(ctx *cli.Context) error {
setLogLevel(logLevel)
}

if err := parseOpts(ctx, &cfg); err != nil {
if err := parseOpts(ctx, &cfg, os.Environ()); err != nil {
return err
}

Expand Down
4 changes: 3 additions & 1 deletion pkg/cli/plan.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cli

import (
"os"

"github.com/suzuki-shunsuke/tfcmt/pkg/controller"
"github.com/suzuki-shunsuke/tfcmt/pkg/terraform"
"github.com/urfave/cli/v2"
Expand All @@ -19,7 +21,7 @@ func cmdPlan(ctx *cli.Context) error {
setLogLevel(logLevel)
}

if err := parseOpts(ctx, &cfg); err != nil {
if err := parseOpts(ctx, &cfg, os.Environ()); err != nil {
return err
}

Expand Down
18 changes: 16 additions & 2 deletions pkg/cli/var.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ import (
"github.com/urfave/cli/v2"
)

func parseVars(vars []string, envs []string, varsM map[string]string) error {
parseVarEnvs(envs, varsM)
return parseVarOpts(vars, varsM)
}

func parseVarOpts(vars []string, varsM map[string]string) error {
for _, v := range vars {
a := strings.Index(v, ":")
Expand All @@ -19,7 +24,16 @@ func parseVarOpts(vars []string, varsM map[string]string) error {
return nil
}

func parseOpts(ctx *cli.Context, cfg *config.Config) error {
func parseVarEnvs(envs []string, m map[string]string) {
for _, kv := range envs {
k, v, _ := strings.Cut(kv, "=")
if a := strings.TrimPrefix(k, "TFCMT_VAR_"); k != a {
m[a] = v
}
}
}

func parseOpts(ctx *cli.Context, cfg *config.Config, envs []string) error {
if owner := ctx.String("owner"); owner != "" {
cfg.CI.Owner = owner
}
Expand Down Expand Up @@ -50,7 +64,7 @@ func parseOpts(ctx *cli.Context, cfg *config.Config) error {

vars := ctx.StringSlice("var")
vm := make(map[string]string, len(vars))
if err := parseVarOpts(vars, vm); err != nil {
if err := parseVars(vars, envs, vm); err != nil {
return err
}
cfg.Vars = vm
Expand Down

0 comments on commit f2bef37

Please sign in to comment.