exec

package
v1.11.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 16, 2026 License: MIT Imports: 17 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ExecCmd = &cobra.Command{
	Use:   "exec [flags] [USER@]SERVER [--] COMMAND...",
	Short: "Execute a command on a remote server",
	Long: `Execute a command on a remote server.

This command executes a specified command on a remote server and returns the output.
It supports SSH-like syntax for specifying the user and server.

Use -- to separate alpacon flags from the remote command, ensuring that flags
intended for the remote command (e.g., -U, -d) are not interpreted as alpacon flags.

All flags must be placed before the server name.

Subcommand names (ls, logs) win over a server of the same name. To reach a server
literally named 'ls' or 'logs', put -- before it: alpacon exec -- ls uptime

Shell metacharacters (;, |, &, $) pass through unquoted to the remote shell.
To send a literal metacharacter, wrap the argument in quotes:
  alpacon exec server 'echo hello;world'

Flags:
  -u, --username [USER_NAME]    Specify the username for command execution.
  -g, --groupname [GROUP_NAME]  Specify the group name for command execution.
  --env="KEY"                   Pass an environment variable to the remote command,
                                reading its value from the current shell. This keeps
                                the value off your local alpacon command line—use it
                                for secrets such as passwords or tokens.
  --env="KEY=VALUE"             Set 'KEY' to a literal value. Discouraged: the value
                                stays on your local alpacon command line, so it lands
                                in shell history, ps output, and CI job logs. Never
                                pass credentials this way.
  --work-session [UUID]         Attach this command to a work-session.
                                Overrides the workspace's active session set via
                                'alpacon work-session use'.
  --detach                      Submit the command and return immediately without
                                waiting for completion. Prints the job ID to stdout.
                                Use 'alpacon exec logs JOB_ID' to retrieve the result.
  --wait                        When a sudo command needs human approval, block and
                                re-attempt until a reviewer approves it in the Alpacon
                                console (web), or the wait times out (default 5m).
  --wait-approval DURATION      Like --wait with a custom wait timeout (e.g. 30m;
                                default 5m). Implies --wait.

Exit code 3 indicates a WorkSession gate denial; run with --output json to
parse a machine-readable diagnostic on stderr.
Exit code 4 indicates the sudo command is pending human approval (approve it in
the Alpacon console, then re-run, or pass --wait to block—--wait-approval
DURATION to block with a longer timeout); --output json emits
{"status":"pending_approval", ...} on stdout.
The server rejects a command whose command line carries a credential—a
-p/--password flag, a KEY=VALUE secret such as PGPASSWORD=..., or a
user:pass@host connection string—before it runs, with exit code 1. Pass the
secret with --env="KEY" instead; --output json emits an error envelope on
stderr with error_code command_inline_credential.
Requires an active WorkSession when using Browser login (Auth0); Token auth (API token or Service token) bypasses this requirement.`,
	Example: `  # Simple command execution
  alpacon exec prod-docker docker ps
  alpacon exec root@prod-docker docker ps

  # Use -- to pass flags to the remote command
  alpacon exec root@db-server -- docker exec postgres psql -U myproject -d myproject
  alpacon exec my-server -- grep -r "pattern" /var/log

  # Specify user and group with flags
  alpacon exec -u root prod-docker systemctl status nginx
  alpacon exec -g docker user@server docker images

  # Pass a secret via the shell env; the value stays off the alpacon command line.
  # Read it in rather than typing it inline, so it stays out of shell history too.
  # psql reads PGPASSWORD from the environment, so it never reaches the remote argv.
  printf 'PGPASSWORD: ' && read -rs PGPASSWORD && export PGPASSWORD
  alpacon exec --env="PGPASSWORD" db-server -- psql -h localhost -U app -c 'SELECT 1'

  # Submit a command asynchronously and retrieve the result later
  alpacon exec --detach web-server -- apt-get update
  alpacon exec logs <JOB_ID>

  # Block up to 30 minutes for a reviewer to approve a sudo command
  alpacon exec --wait-approval 30m root@prod-docker -- systemctl restart nginx`,

	DisableFlagParsing: true,
	Run: func(cmd *cobra.Command, args []string) {
		parsed := ParseRemoteExecArgs(args)

		if parsed.ShowHelp {
			_ = cmd.Help()
			return
		}

		if parsed.Err != "" {
			utils.CliErrorWithExit("%s", parsed.Err)
			return
		}

		if parsed.Server == "" {
			_ = cmd.Help()
			utils.CliErrorWithExit("server name is required.")
			return
		}

		if parsed.Command == "" {
			utils.CliErrorWithExit("You must specify a command to execute.")
			return
		}

		RunRemoteExec(parsed)
	},
}

Functions

func AddListFlags added in v1.9.2

func AddListFlags(cmd *cobra.Command)

AddListFlags and RunListFromFlags are exported for the deprecated 'alpacon event', which delegates here. Both live in this file so the flag names exist in exactly one place.

func HandleCommandResult added in v1.4.8

func HandleCommandResult(err error, invokedAs Invocation)

HandleCommandResult exits appropriately on error. Output is streamed to stdout during execution; on a remote failure the error carries that output, used here only to surface the sudo-denial hint (not re-printed). invokedAs names the command the user ran so a hint can quote it; empty falls back to exec.

func HandlePendingApproval added in v1.7.2

func HandlePendingApproval(err error, reRunHint utils.NextAction) bool

HandlePendingApproval emits the structured pending-approval feedback for a command left pending human approval and not waited on—either a job the server parked at awaiting_approval (PendingApprovalError) or a sudo denial with an approval request in flight—then exits with ExitCodePendingApproval. It reports true when it handled the err; the caller skips its normal result handling on true. Neither path carries an approval request id, so the machine signal omits it. reRunHint is the exact command the caller invoked (with any --env caveat in its Description), so a human can copy-paste it once the request is approved.

func ParseEnvArg added in v1.9.0

func ParseEnvArg(arg string, env map[string]string) string

ParseEnvArg parses a --env token into env. A bare KEY reads the shell value, warning and skipping if unset; malformed input returns an error message.

func RunCommandWithRetry added in v1.3.2

func RunCommandWithRetry(ac *client.AlpaconClient, serverName, command, username, groupname string, env map[string]string, workSessionID string, out io.Writer) error

RunCommandWithRetry executes a remote command with MFA/username-required error handling and retry logic, streaming output to out. workSessionID is forwarded as the work_session field; pass "" to omit it.

func RunExecWithApprovalWait added in v1.7.2

func RunExecWithApprovalWait(ac *client.AlpaconClient, serverName, command, username, groupname string, env map[string]string, workSessionID string, waitTimeout time.Duration, out io.Writer) error

RunExecWithApprovalWait runs a command via RunExecWithPresenceStepUp and, when it is denied with an approval request in flight (a pendingApproval code) and waitTimeout is positive, blocks and re-attempts the command on a fixed interval until a reviewer approves it out of band (the re-run then succeeds or hits a different, terminal denial), or the bounded timeout elapses. When waitTimeout is zero or negative, or the denial carries a terminal code, it returns the first err unchanged so the caller's pending/denial handling runs.

Re-attempting the command is the only poll available here: the plugin's denial line carries the denial code but no approval request id, and this credential channel has no approval-status endpoint to query (ADR 0015 moves approval out of band). Re-running is side-effect-safe: a sudo command pending approval is denied by the server and never executes, so each poll tick is a no-op denial until a reviewer approves, at which point the command runs exactly once. The poll mirrors the MFA step-up structure (api/mfa/mfa.go): a spinner, a fixed-interval ticker, and a precise deadline.

func RunExecWithPresenceStepUp added in v1.7.2

func RunExecWithPresenceStepUp(ac *client.AlpaconClient, serverName, command, username, groupname string, env map[string]string, workSessionID string, out io.Writer) error

RunExecWithPresenceStepUp runs a command via RunCommandWithRetry and, when it is denied for a missing recent MFA (SUDO_PRESENCE_REQUIRED) on an interactive terminal, offers an MFA step-up and retries once. Non-interactive callers (scripts, CI, AI agents) fall through unchanged so HandleCommandResult prints the static denial hint; non-interactive humans additionally get the verification link they can complete out of band. Reached via RunRemoteExec by exec and websh command mode; interactive websh keeps its own sudo MFA flow.

func RunListFromFlags added in v1.9.2

func RunListFromFlags(cmd *cobra.Command)

RunListFromFlags requires the flag set registered by AddListFlags.

func RunRemoteExec added in v1.9.0

func RunRemoteExec(parsed RemoteExecArgs)

RunRemoteExec is the shared post-parse execution path for exec and websh command mode. Requires Server and Command to be non-empty.

func ShellJoin added in v1.4.8

func ShellJoin(parts []string) string

ShellJoin reassembles tokenized command parts into a single string. Parts containing whitespace or single quotes are re-quoted to preserve argument boundaries; metacharacters pass through for the remote shell. A single-element slice is returned as-is (already a formed command line).

Types

type Invocation added in v1.9.2

type Invocation string

Invocation names the command the user ran, so a hint can show an example they can copy without translating it first. A defined type rather than a bare string, so an arbitrary string variable cannot reach it without a conversion that names the intent. Websh command mode reaches this package through RemoteExecArgs.InvokedAs; the zero value renders as exec.

const (
	ExecInvocation  Invocation = "alpacon exec"
	WebshInvocation Invocation = "alpacon websh"
)

ExecInvocation and WebshInvocation are the two Invocation values (see the Invocation type below).

type RemoteExecArgs added in v1.3.2

type RemoteExecArgs struct {
	Username      string
	Groupname     string
	WorkSessionID string
	OutputFormat  string
	Server        string
	Command       string
	// InvokedAs selects which syntax a hint renders its example in. The caller
	// sets it, not ParseRemoteExecArgs: websh command mode marks its args
	// WebshInvocation, and exec leaves it empty, which the hint reads as exec.
	InvokedAs    Invocation
	Env          map[string]string
	WaitApproval time.Duration
	Detach       bool
	Wait         bool
	ShowHelp     bool
	Err          string
}

RemoteExecArgs holds parsed arguments for remote command execution.

func ParseRemoteExecArgs added in v1.3.2

func ParseRemoteExecArgs(args []string) RemoteExecArgs

ParseRemoteExecArgs parses raw CLI arguments with manual flag handling. It recognizes -u/--username, -g/--groupname, and -h/--help flags before the server name.

The -- separator has two roles depending on position:

  • After the server name: acts as a command separator. Everything after it is the remote command, with no further flag parsing.
  • Before the server name (e.g., after flags): acts as an end-of-flags marker. The first arg after -- becomes the server, the rest is the command.

Without --, everything after the server name is the remote command.

Layout: [flags] [USER@]SERVER [--] COMMAND...

func (RemoteExecArgs) WaitTimeout added in v1.9.1

func (a RemoteExecArgs) WaitTimeout() time.Duration

WaitTimeout returns the effective approval-wait timeout, or 0 when not waiting.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL