Skip to content
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
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,25 @@ envctl export --format env # KEY=VALUE
envctl export --format json # {"KEY": "VALUE"}
```

### Several Applications in One Run

`--apps` exports several applications as one JSON object keyed by
application name. It needs `--format json` and a config with
`applications:`. A secret that more than one application includes is read
from the backend once per run, so a 1Password config authorizes once
instead of once per application:

```bash
envctl export --apps api,worker,web --env local --format json
# {"api": {"KEY": "VALUE"}, "web": {...}, "worker": {...}}
```

Each application keeps its own values, so a key that two applications
resolve differently stays correct in each. The run fails as a whole if any
application fails, and prints nothing. A tool that starts several services
(a Tilt or Skaffold dev loop, a test harness) can call this once and hand
each service its own object.

### Inspect Secrets

```bash
Expand Down Expand Up @@ -1010,6 +1029,8 @@ envctl export [flags]

Flags:
--format FORMAT Output format: env, shell, json (default: shell)
--apps A,B Export these applications as {"app": {"KEY": "VALUE"}};
needs --format json, can't be combined with --app
```

#### `envctl list`
Expand Down
59 changes: 59 additions & 0 deletions internal/cmd/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,22 @@
package cmd

import (
"context"
"errors"
"fmt"
"os"
"slices"

"github.com/sentiolabs/envctl/internal/env"
"github.com/sentiolabs/envctl/internal/output"
"github.com/sentiolabs/envctl/internal/secrets"
"github.com/spf13/cobra"
)

// Command flags and definition for export command.
var (
exportFormat string
exportApps []string

// exportCmd outputs secrets in env, shell, or json format.
exportCmd = &cobra.Command{
Expand All @@ -29,6 +36,11 @@ Example:
eval "$(envctl export --format shell)"
envctl export --format json | jq .

--apps exports several applications in one run as {"app": {"KEY": "VALUE"}}.
It needs --format json. A secret that two applications include is read
from the backend once, so a 1Password-backed config authorizes once:
envctl export --apps api,web --env local --format json

Sources with file.path are written and their path_as variables included.
Sources with file.name are skipped: only envctl run materializes them.`,
RunE: runExport,
Expand All @@ -38,6 +50,9 @@ Sources with file.name are skipped: only envctl run materializes them.`,
// init registers the export command with the root command.
func init() {
exportCmd.Flags().StringVar(&exportFormat, "format", "shell", "output format (env, shell, json)")
exportCmd.Flags().StringSliceVar(&exportApps, "apps", nil,
"export these applications as one JSON object keyed by name (needs --format json)")
_ = exportCmd.RegisterFlagCompletionFunc("apps", completeApplicationNames)
rootCmd.AddCommand(exportCmd)
}

Expand All @@ -50,10 +65,54 @@ func runExport(cmd *cobra.Command, args []string) error {
return err
}

if len(exportApps) > 0 {
return runExportApps(ctx, cmd, format)
}

entries, _, err := loadAndBuild(ctx, cmd, nil)
if err != nil {
return err
}

return output.Write(os.Stdout, entries, format)
}

// runExportApps builds each --apps application with one shared memo and
// writes them as a single JSON object. Any application's failure fails the
// whole export, so a caller never gets a partial object.
func runExportApps(ctx context.Context, cmd *cobra.Command, format output.Format) error {
if format != output.FormatJSON {
return fmt.Errorf("--apps needs --format json (got %s)", format)
}
if appName != "" {
return errors.New("--apps and --app can't be combined")
}
// An empty name would resolve to the default (or a random) application
// and land in the output under the key "".
if slices.Contains(exportApps, "") {
return errors.New("--apps has an empty application name")
}

configPath, cfg, err := loadConfig()
if err != nil {
return err
}
if !cfg.HasApplications() {
return errors.New("--apps needs a config with applications")
}

memo := secrets.NewMemo()
apps := make(map[string][]env.Entry, len(exportApps))
for _, application := range slices.Compact(slices.Sorted(slices.Values(exportApps))) {
out, err := buildApp(ctx, cmd, appBuild{
cfg: cfg, configPath: configPath, application: application,
mode: sinkModePersistentOnly, memo: memo,
})
if err != nil {
return fmt.Errorf("application %s: %w", application, err)
}
apps[application] = out.entries
}

return output.WriteJSONApps(os.Stdout, apps)
}
131 changes: 131 additions & 0 deletions internal/cmd/export_apps_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
//nolint:testpackage // Testing internal functions requires same package
package cmd

import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"

"github.com/sentiolabs/envctl/internal/mocks"
"github.com/sentiolabs/envctl/internal/output"
"github.com/sentiolabs/envctl/internal/secrets"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)

// Two applications that both include "shared", the way bacstack's api and
// web items both pull a shared 1Password item. include_all lets each source
// contribute every key.
const appsConfig = `version: 1
include_all: true
default_application: api
default_environment: dev
applications:
api:
dev:
- secret: api/dev
- secret: shared
- secret: core
keys:
- key: TENANT
web:
dev:
- secret: web/dev
- secret: shared
- secret: core
keys:
- key: TENANT
`

// Applications and keys the --apps tests share.
const (
appAPI = "api"
appWeb = "web"
keyRole = "ROLE"
keyShared = "SHARED"
)

// setupAppsExport points the CLI at appsConfig and installs client as every
// backend, restoring the package globals on cleanup.
func setupAppsExport(t *testing.T, client secrets.Client) {
t.Helper()
path := filepath.Join(t.TempDir(), ".envctl.yaml")
require.NoError(t, os.WriteFile(path, []byte(appsConfig), 0o600))

prevConfig, prevEnv, prevApp := configFile, envName, appName
prevFormat, prevApps, prevFactory := exportFormat, exportApps, newSecretsClient
t.Cleanup(func() {
configFile, envName, appName = prevConfig, prevEnv, prevApp
exportFormat, exportApps, newSecretsClient = prevFormat, prevApps, prevFactory
})
configFile, envName, appName = path, testDevEnv, ""
exportFormat = string(output.FormatJSON)
newSecretsClient = func(context.Context, secrets.Options) (secrets.Client, error) {
return client, nil
}
}

func TestExportApps_ReadsSharedSecretsOnce(t *testing.T) {
client := mocks.NewMockClient(t)
client.On("Name").Return("mock").Maybe()
// .Once() fails the test if a second application reaches the backend
// again for a secret the first one already read.
client.On("GetSecret", mock.Anything, "api/dev").Return(map[string]string{keyRole: appAPI}, nil).Once()
client.On("GetSecret", mock.Anything, "web/dev").Return(map[string]string{keyRole: appWeb}, nil).Once()
client.On("GetSecret", mock.Anything, "shared").Return(map[string]string{keyShared: "s"}, nil).Once()
client.On("GetSecretKey", mock.Anything, "core", "TENANT").Return("t1", nil).Once()
setupAppsExport(t, client)
exportApps = []string{appWeb, appAPI}

stdout, err := captureStdout(t, func() error { return runExport(exportCmd, nil) })
require.NoError(t, err)

var got map[string]map[string]string
require.NoError(t, json.Unmarshal([]byte(stdout), &got), stdout)
assert.Equal(t, map[string]map[string]string{
appAPI: {keyRole: appAPI, keyShared: "s", "TENANT": "t1"},
appWeb: {keyRole: appWeb, keyShared: "s", "TENANT": "t1"},
}, got)
}

func TestExportApps_NeedsJSON(t *testing.T) {
setupAppsExport(t, mocks.NewMockClient(t))
exportApps = []string{appAPI}
exportFormat = string(output.FormatShell)

err := runExport(exportCmd, nil)
require.ErrorContains(t, err, "--apps needs --format json")
}

func TestExportApps_RejectsApp(t *testing.T) {
setupAppsExport(t, mocks.NewMockClient(t))
exportApps = []string{appAPI}
appName = appWeb

err := runExport(exportCmd, nil)
require.ErrorContains(t, err, "--apps and --app can't be combined")
}

func TestExportApps_RejectsEmptyName(t *testing.T) {
setupAppsExport(t, mocks.NewMockClient(t))
exportApps = []string{appAPI, "", appWeb}

err := runExport(exportCmd, nil)
require.ErrorContains(t, err, "--apps has an empty application name")
}

func TestExportApps_UnknownAppFailsWholeExport(t *testing.T) {
client := mocks.NewMockClient(t)
client.On("Name").Return("mock").Maybe()
client.On("GetSecret", mock.Anything, mock.Anything).Return(map[string]string{"K": "v"}, nil).Maybe()
client.On("GetSecretKey", mock.Anything, mock.Anything, mock.Anything).Return("v", nil).Maybe()
setupAppsExport(t, client)
exportApps = []string{appAPI, "missing"}

stdout, err := captureStdout(t, func() error { return runExport(exportCmd, nil) })
require.ErrorContains(t, err, "application missing")
assert.Empty(t, stdout, "a failed export must not print a partial object")
}
54 changes: 46 additions & 8 deletions internal/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -310,8 +310,16 @@ func resolveConfigPath() (string, error) {
// resolveEnvironmentConfig resolves the environment config based on mode.
// Returns the environment config and, if in application mode, the application config.
func resolveEnvironmentConfig(cfg *config.Config) (*config.Environment, *config.Application, error) {
return resolveEnvironmentConfigFor(cfg, appName)
}

// resolveEnvironmentConfigFor is resolveEnvironmentConfig for a named
// application instead of the --app flag. Legacy configs ignore application.
func resolveEnvironmentConfigFor(
cfg *config.Config, application string,
) (*config.Environment, *config.Application, error) {
if cfg.HasApplications() {
env, app, err := cfg.GetApplicationEnvironment(appName, envName)
env, app, err := cfg.GetApplicationEnvironment(application, envName)
if err != nil {
return nil, nil, err
}
Expand Down Expand Up @@ -352,18 +360,47 @@ func loadAndBuildFiles(
overrides map[string]string,
mode sinkMode,
) (*buildOutput, error) {
configPath, err := resolveConfigPath()
configPath, cfg, err := loadConfig()
if err != nil {
return nil, err
}
return buildApp(ctx, cmd, appBuild{
cfg: cfg, configPath: configPath, application: appName, overrides: overrides, mode: mode,
})
}

// loadConfig finds and parses the config the --config flag names.
func loadConfig() (string, *config.Config, error) {
configPath, err := resolveConfigPath()
if err != nil {
return "", nil, err
}
verboseLog("Using config: %s", configPath)

cfg, err := config.Load(configPath)
if err != nil {
return nil, err
return "", nil, err
}
return configPath, cfg, nil
}

// appBuild is one application's build inside an already loaded config.
type appBuild struct {
cfg *config.Config
configPath string
application string
overrides map[string]string
mode sinkMode
// memo is shared by every application built in one invocation. Nil
// leaves every read going to the backend.
memo *secrets.Memo
}

envConfig, app, err := resolveEnvironmentConfig(cfg)
// buildApp resolves one application's entries and file sinks, writes the
// sinks according to mode, and merges their path variables into the entries.
func buildApp(ctx context.Context, cmd *cobra.Command, in appBuild) (*buildOutput, error) {
cfg, configPath := in.cfg, in.configPath
envConfig, app, err := resolveEnvironmentConfigFor(cfg, in.application)
if err != nil {
return nil, err
}
Expand All @@ -378,17 +415,18 @@ func loadAndBuildFiles(
if err != nil {
return nil, err
}
client = in.memo.Wrap(client, secrets.Scope(cfg, envConfig))

builder := env.NewBuilder(client, cfg, appName, envName).
builder := env.NewBuilder(client, cfg, in.application, envName).
WithIncludeAll(getIncludeAllOverride(cmd)).
WithOptions(env.BuilderOptions{NoCache: noCache, Refresh: refresh})
WithOptions(env.BuilderOptions{NoCache: noCache, Refresh: refresh, Memo: in.memo})

result, err := builder.BuildWithFiles(ctx, overrides)
result, err := builder.BuildWithFiles(ctx, in.overrides)
if err != nil {
return nil, err
}

files, err := materializeFiles(result.Files, cfg.ResolveFilesDirAs(app), filepath.Dir(configPath), mode)
files, err := materializeFiles(result.Files, cfg.ResolveFilesDirAs(app), filepath.Dir(configPath), in.mode)
if err != nil {
return nil, err
}
Expand Down
11 changes: 11 additions & 0 deletions internal/docs/content/patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,3 +224,14 @@ Later sources in the list override earlier ones when keys conflict.
You can also use inline aws: or 1pass: blocks on source entries for
per-source overrides (region, profile, vault) without needing the
backend: routing hint.

Several Applications at Once
----------------------------

A dev loop that starts several services can fetch all of them in one run:

envctl export --apps api,worker,web --env local --format json

The output is {"app": {"KEY": "VALUE"}}, one object per application. A
secret shared by several applications is read from the backend once, so
1Password prompts once. Any failing application fails the whole run.
Loading
Loading