Skip to content

Commit

Permalink
fix: all-namespaces support (#148)
Browse files Browse the repository at this point in the history
Signed-off-by: chenk <hen.keinan@gmail.com>
  • Loading branch information
chen-keinan authored Apr 20, 2023
1 parent 7e427c2 commit 019a895
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
8 changes: 7 additions & 1 deletion examples/trivy.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,13 @@ func main() {
log.Fatal(err)
}
printArtifacts(artifacts)

fmt.Println("Scanning all namespaces ")
artifacts, err = trivyk8s.AllNamespaces().ListArtifacts(ctx)
if err != nil {
log.Fatal(err)
}
printArtifacts(artifacts)

fmt.Println("Scanning namespace 'default', resource 'deployment/orion'")

//trivy k8s --namespace default deployment/orion
Expand Down
25 changes: 20 additions & 5 deletions pkg/trivyk8s/trivyk8s.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
// TrivyK8S interface represents the operations supported by the library
type TrivyK8S interface {
Namespace(string) TrivyK8S
AllNamespaces() TrivyK8S
Resources(string) TrivyK8S
ArtifactsK8S
}
Expand All @@ -42,10 +43,11 @@ type ArtifactsK8S interface {
}

type client struct {
cluster k8s.Cluster
namespace string
resources []string
logger *zap.SugaredLogger
cluster k8s.Cluster
namespace string
resources []string
allNamespaces bool
logger *zap.SugaredLogger
}

// New creates a trivyK8S client
Expand All @@ -59,6 +61,12 @@ func (c *client) Namespace(namespace string) TrivyK8S {
return c
}

// Namespace configure the namespace to execute the queries
func (c *client) AllNamespaces() TrivyK8S {
c.allNamespaces = true
return c
}

// Resource configure which resources to execute the queries
func (c *client) Resources(resources string) TrivyK8S {
if len(resources) == 0 {
Expand All @@ -70,11 +78,18 @@ func (c *client) Resources(resources string) TrivyK8S {
return c
}

func isNamspaced(namespace string, allNamespace bool) bool {
if len(namespace) != 0 || (len(namespace) == 0 && allNamespace) {
return true
}
return false
}

// ListArtifacts returns kubernetes scannable artifacs.
func (c *client) ListArtifacts(ctx context.Context) ([]*artifacts.Artifact, error) {
artifactList := make([]*artifacts.Artifact, 0)

namespaced := len(c.namespace) != 0
namespaced := isNamspaced(c.namespace, c.allNamespaces)
grvs, err := c.cluster.GetGVRs(namespaced, c.resources)
if err != nil {
return nil, err
Expand Down

0 comments on commit 019a895

Please sign in to comment.