Open-Source Wikis

/

Trivy

/

Apps

/

CLI

aquasecurity/trivy

CLI

Active contributors: knqyf263, DmitriyLewen, simar7, afdesk

Purpose

The Trivy CLI is the user-facing entry point. It is a Cobra-based command tree that selects an artifact handler, configures a scan, runs it, and writes a report. The CLI binary is built from cmd/trivy/main.go and the command tree is defined in pkg/commands/app.go.

Directory layout

cmd/
└── trivy/
    └── main.go                # entry point; ~50 lines
pkg/
└── commands/
    ├── app.go                 # Cobra root + every subcommand constructor (~1500 lines)
    ├── run.go                 # commands.Run shim
    ├── signal.go              # SIGINT/SIGTERM handling
    ├── artifact/
    │   ├── run.go             # the shared scan runner (~750 lines)
    │   └── scanner.go         # scan service factory (~400 lines)
    ├── auth/                  # `trivy registry login/logout`
    ├── clean/                 # `trivy clean`
    ├── convert/               # `trivy convert`
    ├── operation/             # cache + DB lifecycle helpers
    └── server/                # `trivy server` and `trivy client`

Key abstractions

Symbol File Purpose
func main() cmd/trivy/main.go Process entrypoint; dispatches to plugin replacement or commands.Run.
commands.Run pkg/commands/run.go Builds the root command and runs it.
NewApp pkg/commands/app.go Builds the root Cobra command and attaches every subcommand.
NewRootCommand pkg/commands/app.go Configures persistent pre-run hooks, version printing, and global flag binding.
flag.GlobalFlagGroup pkg/flag/global_flags.go Shared flags (--config, --debug, --quiet, --cache-dir, etc.).
artifact.Run pkg/commands/artifact/run.go The shared runner used by every scan-shaped command.
artifact.NewScanner pkg/commands/artifact/scanner.go Factory that builds a scan.Service for a given target type.
loadPluginCommands pkg/commands/app.go Discovers installed plugins and exposes them as subcommands.
commands.NotifyContext pkg/commands/signal.go Wraps the root context for graceful shutdown on SIGINT/SIGTERM.

Command tree

The root command (trivy) defines three groups: Scanning Commands, Management Commands, and Utility Commands. The full subcommand list:

Command Constructor Purpose
trivy image NewImageCommand Scan a container image (registry, daemon, tar).
trivy filesystem (alias fs) NewFilesystemCommand Scan a local directory tree.
trivy rootfs NewRootfsCommand Scan an extracted root filesystem.
trivy repo (alias repository) NewRepositoryCommand Scan a Git repository (local or remote).
trivy vm NewVMCommand Scan a virtual-machine image.
trivy kubernetes (alias k8s) NewKubernetesCommand Scan a Kubernetes cluster (see pkg/k8s/).
trivy sbom NewSBOMCommand Scan a CycloneDX or SPDX SBOM file.
trivy server NewServerCommand Run as an RPC server (see server).
trivy client NewClientCommand (Legacy) RPC client; --server flags on other commands are preferred.
trivy config NewConfigCommand Misconfiguration-only scan.
trivy convert NewConvertCommand Convert a Trivy JSON report to another format.
trivy plugin NewPluginCommand Install, list, run, and uninstall plugins.
trivy module NewModuleCommand Install/list/uninstall WASM modules.
trivy clean NewCleanCommand Wipe cache, DB, and policy directories.
trivy registry NewRegistryCommand trivy registry login/logout.
trivy vex NewVEXCommand VEX repository management (see pkg/vex/repo/).
trivy version NewVersionCommand Print version, DB metadata, plugin index.
trivy auth (legacy alias) Older auth subcommand (kept for compatibility).
trivy <plugin> dynamic Discovered at runtime via loadPluginCommands.

Plugin commands are added under a dedicated Plugin Commands group at startup if any plugins are installed. The "plugin runtime" mode where Trivy is the plugin (rather than running one) is triggered by TRIVY_RUN_AS_PLUGIN and dispatched by cmd/trivy/main.go before Cobra is even constructed.

How a scan is wired

sequenceDiagram
    participant User
    participant Main as cmd/trivy/main.go
    participant Run as commands.Run
    participant Cobra as Cobra root
    participant Sub as Subcommand RunE
    participant Runner as artifact.Run
    participant Scanner as artifact.NewScanner
    participant Service as scan.Service

    User->>Main: trivy image alpine:latest
    Main->>Run: commands.Run(ctx)
    Run->>Cobra: NewApp().Execute()
    Cobra->>Sub: image.RunE
    Sub->>Sub: build flag.Options
    Sub->>Runner: artifact.Run(ctx, opts, target)
    Runner->>Scanner: NewScanner(opts, target)
    Scanner->>Service: scan.NewService(backend, artifact)
    Runner->>Service: ScanArtifact(ctx, opts)
    Service-->>Runner: types.Report
    Runner->>Runner: VEX filter, write report
    Runner-->>User: stdout / file output

The split between pkg/commands/app.go (one place that defines every command) and pkg/commands/artifact/run.go (one place that runs every scan) is the secret to keeping the CLI compact: each subcommand is mostly flag plumbing.

Flag system

The CLI uses a custom flag layer in pkg/flag/:

  1. flag.NewGlobalFlagGroup() produces global flags (--config-file, --debug, --cache-dir, etc.).
  2. Each subcommand composes additional groups (e.g., image flags, scan flags, report flags).
  3. flags.AddFlags(cmd) registers them with Cobra/pflag.
  4. flags.Bind(cmd) binds them with viper for env-var and config-file overrides.
  5. Inside RunE, flags.ToOptions() converts the parsed values into a strongly typed flag.Options.

Flag groups present in this repo:

AwsFlagGroup, CacheFlagGroup, CleanFlagGroup, DBFlagGroup, GlobalFlagGroup, ImageFlagGroup, K8sFlagGroup, LicenseFlagGroup, MisconfFlagGroup, ModuleFlagGroup, PackageFlagGroup, RegistryFlagGroup, RegoFlagGroup, RemoteFlagGroup, RepoFlagGroup, ReportFlagGroup, ScanFlagGroup, SecretFlagGroup, VulnerabilityFlagGroup. Each is its own file under pkg/flag/.

Signal handling

pkg/commands/signal.go wraps the root context with signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM). On a second signal, the process exits hard. defer commands.Cleanup() in cmd/trivy/main.go ensures temp files and DB locks are released even on cancellation.

Plugin replacement mode

When the binary is invoked with TRIVY_RUN_AS_PLUGIN=<name> set, cmd/trivy/main.go skips Cobra entirely and dispatches directly to plugin.Run. This lets the plugin manager re-execute the same binary as if it were a separate program, simplifying signing and caching.

Integration points

  • fanal (pkg/fanal/) — chosen by the artifact runner based on the target type.
  • Scan service (pkg/scan/) — the engine the runner drives.
  • Cache (pkg/cache/) — initialized by the runner from --cache-backend and --cache-dir flags.
  • DB (pkg/db/) — refreshed at runner startup unless --skip-db-update is set.
  • Policy (pkg/policy/) — Trivy Checks bundle for IaC scans.
  • Report writers (pkg/report/) — the runner picks one based on --format.
  • VEX (pkg/vex/) — applied between scan and write when --vex is set.

Entry points for modification

  • Adding a top-level subcommand — add New<Name>Command in pkg/commands/app.go and call rootCmd.AddCommand(...) in NewApp. If the subcommand performs a scan, route to pkg/commands/artifact/run.go.
  • Adding a global flag — extend pkg/flag/global_flags.go. If it should also live in subcommands' help, add it to the relevant flag group.
  • Adding a target type — implement an artifact.Artifact in a new pkg/fanal/artifact/<type>/ directory and update pkg/commands/artifact/scanner.go to dispatch to it.
  • Adding output format — implement a writer in pkg/report/ and register it in the writer factory.

Key source files

File Purpose
cmd/trivy/main.go Process entry; plugin dispatch; error funneling to exit code.
pkg/commands/run.go commands.Run shim.
pkg/commands/app.go Cobra root and every subcommand constructor.
pkg/commands/signal.go Graceful shutdown.
pkg/commands/artifact/run.go The shared scan runner.
pkg/commands/artifact/scanner.go Builds scan.Service for a given target type.
pkg/commands/clean/clean.go trivy clean implementation.
pkg/commands/convert/convert.go trivy convert implementation.
pkg/commands/auth/auth.go Registry login/logout.
pkg/flag/global_flags.go Global flag definitions.
pkg/flag/options.go The materialized flag.Options struct.

See also

Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.

CLI – Trivy wiki | Factory