Skip to content

Instantly share code, notes, and snippets.

@blzjns
Last active March 29, 2022 22:10
Show Gist options
  • Save blzjns/56f69635bdbf012ce17e637afc37c17e to your computer and use it in GitHub Desktop.
Save blzjns/56f69635bdbf012ce17e637afc37c17e to your computer and use it in GitHub Desktop.
How to use golang templates for generating custom trivy reports

Trivy templating

Trivy uses golang templates. Thus, whenever opening a tag {{an_opening_tag}}, most likely it needs to be closed with {{end}}.

For example:

The tag range works similarly to a for-each loop, where . represents an initial object

{{range . as $myObj}}--- This a text concatenating {{$myObj.Target}} ---{{end}}

Closing a tag {{end}} isn't necessary whenever reading a variable value, or assigning a new variable.

For example:

{{range . as $myObj}}{{$prefixTarget := cat "#" $myObj.Target}}--- This a text concatenating {{$prefixTarget}} ---{{end}}

Generating a custom trivy report

Assume we have template file named yaml.tpl, and it will help us create an YAML structure out of our trivy report:

{{range .}}{{if (contains "someNiceStr" .Target)}}- target: "{{.Target}}"\n\x20\x20vulnerabilities:{{end}}{{range $i, $v := .Vulnerabilities}}\n\x20\x20\x20\x20- id: "{{$v.VulnerabilityID}}"\n{{$uniqueId := cat $v.VulnerabilityID "#" $v.PkgName | replace " " ""}}\x20\x20\x20\x20\x20\x20uniqueId: "{{$uniqueId}}"\n\x20\x20\x20\x20\x20\x20severity: "{{$v.Severity}}"\n\x20\x20\x20\x20\x20\x20title: "{{$v.Title | replace "\x22" "\x27"}}"\n\x20\x20\x20\x20\x20\x20description: "{{$v.Description | replace "\x22" "\x27"}}"\n\x20\x20\x20\x20\x20\x20package: "{{$v.PkgName}}"\n\x20\x20\x20\x20\x20\x20installed_version: "{{$v.InstalledVersion}}"\n\x20\x20\x20\x20\x20\x20fixed_in_version: "{{$v.FixedVersion}}"{{end}}{{end}}

Please note you can escape different characters using ascii codes: http://defindit.com/ascii.html

trivy --format template --template

yaml_template=`cat yaml.tpl`

trivy image --format template --template "$yaml_template" -o trivy_report.yaml <IMAGE_NAME>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment