Created
October 5, 2022 15:46
-
-
Save utix/22de59f3ef4d480ce8d08e3e56f780d9 to your computer and use it in GitHub Desktop.
Simple script to send Vulnerabilities stats to datadog from a trivy json response, `DD_SITE="datadoghq.eu" ./trivy_datadog_stats.py` to use it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Submit metrics returns "Payload accepted" response | |
""" | |
from datetime import datetime | |
import json | |
from datadog_api_client import ApiClient, Configuration | |
from datadog_api_client.v2.api.metrics_api import MetricsApi | |
from datadog_api_client.v2.model.metric_intake_type import MetricIntakeType | |
from datadog_api_client.v2.model.metric_payload import MetricPayload | |
from datadog_api_client.v2.model.metric_point import MetricPoint | |
from datadog_api_client.v2.model.metric_series import MetricSeries | |
from typing import Dict, Tuple | |
def build_body(image: str, stats: Dict[str, int]) -> MetricPayload: | |
series = [] | |
now = int(datetime.now().timestamp()) | |
for severity, count in stats.items(): | |
series.append(MetricSeries( | |
metric="security.image.vulnerabilities", | |
type=MetricIntakeType.COUNT, | |
points=[ | |
MetricPoint( | |
timestamp=now, | |
value=count, | |
), | |
], | |
tags=["severity:"+severity, "image:"+image] | |
)) | |
return MetricPayload(series=series) | |
def get_stats(filename: str) -> Tuple[str, Dict[str, int]]: | |
stats = {} | |
with open(filename) as f: | |
data = json.load(f) | |
for r in data["Results"]: | |
if "Vulnerabilities" not in r: | |
continue | |
for vuln in r["Vulnerabilities"]: | |
severity = vuln["Severity"] | |
if severity in stats: | |
stats[severity] += 1 | |
else: | |
stats[severity] = 1 | |
return data["ArtifactName"], stats | |
raise Exception('cannot open' + filename) | |
configuration = Configuration() | |
with ApiClient(configuration) as api_client: | |
api_instance = MetricsApi(api_client) | |
image, stats = get_stats("result.json") | |
body = build_body(image, stats) | |
response = api_instance.submit_metrics(body=body) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't forget to set DD_API_KEY to have this works cf datadog doc