github.com/devseccon/trivy@v0.47.1-0.20231123133102-bd902a0bd996/pkg/k8s/commands/namespace.go (about)

     1  package commands
     2  
     3  import (
     4  	"context"
     5  
     6  	"golang.org/x/xerrors"
     7  
     8  	"github.com/aquasecurity/trivy-kubernetes/pkg/k8s"
     9  	"github.com/aquasecurity/trivy-kubernetes/pkg/trivyk8s"
    10  	"github.com/devseccon/trivy/pkg/flag"
    11  	"github.com/devseccon/trivy/pkg/log"
    12  )
    13  
    14  // namespaceRun runs scan on kubernetes cluster
    15  func namespaceRun(ctx context.Context, opts flag.Options, cluster k8s.Cluster) error {
    16  	if err := validateReportArguments(opts); err != nil {
    17  		return err
    18  	}
    19  	var trivyk trivyk8s.TrivyK8S
    20  	if opts.AllNamespaces {
    21  		trivyk = trivyk8s.New(cluster, log.Logger).AllNamespaces()
    22  	} else {
    23  		trivyk = trivyk8s.New(cluster, log.Logger).Namespace(getNamespace(opts, cluster.GetCurrentNamespace()))
    24  	}
    25  
    26  	artifacts, err := trivyk.ListArtifacts(ctx)
    27  	if err != nil {
    28  		return xerrors.Errorf("get k8s artifacts error: %w", err)
    29  	}
    30  
    31  	runner := newRunner(opts, cluster.GetCurrentContext())
    32  	return runner.run(ctx, artifacts)
    33  }
    34  
    35  func getNamespace(opts flag.Options, currentNamespace string) string {
    36  	if len(opts.K8sOptions.Namespace) > 0 {
    37  		return opts.K8sOptions.Namespace
    38  	}
    39  
    40  	return currentNamespace
    41  }