id: hadolint-dockerfile-policy-gate
namespace: company.team
description: |
Dockerfiles that carry policy violations, a floating latest tag, a root
final user, unpinned apt packages, merge with nothing standing in the way,
and the damage surfaces later as drifted production rebuilds. This flow
starts when CI POSTs that a pull request was opened, lints the Dockerfile
with hadolint inside its official container, grades every finding by
severity against a configured fail level, and escalates a failing or
unparsable report to a GitHub issue and a Slack alert while a clean run
logs the all-clear. The verdict, the per-severity counts, the rule codes,
and the raw report URI are published as flow outputs that any merge gate
downstream can consume.
triggers:
- id: pull_request_opened
type: io.kestra.plugin.core.trigger.Webhook
description: CI POSTs here when a pull request touches a Dockerfile, carrying
the repository full name and PR number as webhook inputs.
key: "{{ secret('HADOLINT_WEBHOOK_KEY') }}"
inputs:
github_repository: "{{ trigger.body.repository.full_name ?? 'your-org/container-images' }}"
pull_request: "{{ trigger.body.pull_request.number ?? '412' }}"
- id: nightly_policy_sweep
type: io.kestra.plugin.core.trigger.Schedule
description: Disabled nightly sweep that re-lints the bundled Dockerfile, a
rehearsal net that stays dark until an operator switches it on.
cron: "0 3 * * *"
disabled: true
inputs:
- id: github_repository
type: STRING
defaults: your-org/container-images
description: Repository in owner/repo form that receives the failure issue when
the gate trips.
- id: pull_request
type: STRING
defaults: "412"
description: Pull request number carried into the issue title, the issue body,
and the Slack message.
- id: fail_on_level
type: STRING
defaults: info
description: Lowest severity that fails the gate (error, warning, info, or
style), defaulting to the same threshold hadolint itself ships with.
tasks:
# --- 1. lint the Dockerfile in the hadolint container ---
- id: lint_workspace
type: io.kestra.plugin.core.flow.WorkingDirectory
description: One shared directory so the JSON report the linter writes and the
parser that grades it read the same file.
tasks:
- id: run_hadolint
type: io.kestra.plugin.scripts.shell.Commands
description: Write the Dockerfile under review with a heredoc, run hadolint with
JSON output, and absorb the tool exit code so only the parsed verdict
below can fail the gate.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
entryPoint: []
containerImage: hadolint/hadolint:latest-alpine
env:
PR_NUMBER: "{{ inputs.pull_request }}"
outputFiles:
- hadolint-report.json
commands:
- |
set -u
cat > Dockerfile <<'DOCKERFILE'
FROM ubuntu:latest
MAINTAINER platform-team@example.com
RUN apt-get update && apt-get install -y curl
USER root
ADD config.yml /etc/app/config.yml
COPY dist/ /app/
EXPOSE 8080
CMD ["/app/entrypoint.sh"]
DOCKERFILE
if ! command -v hadolint > /dev/null 2>&1; then
echo "hadolint is missing from the container image" >&2
exit 1
fi
echo "linting the Dockerfile for pull request ${PR_NUMBER}"
hadolint --format json Dockerfile > hadolint-report.json || true
if [ ! -s hadolint-report.json ]; then
echo "[]" > hadolint-report.json
echo "hadolint returned no findings, recording an empty report"
fi
echo "report bytes $(wc -c < hadolint-report.json)"
- id: parse_report
type: io.kestra.plugin.scripts.python.Script
description: Grade every finding against the fail level, count style, info,
warning, and error hits, and emit the verdict through the outputs
protocol.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: python:3.12-slim
env:
FAIL_ON_LEVEL: "{{ inputs.fail_on_level }}"
PULL_REQUEST: "{{ inputs.pull_request }}"
GITHUB_REPOSITORY: "{{ inputs.github_repository }}"
script: |
import json
import os
RANK = {"style": 0, "info": 1, "warning": 2, "error": 3}
FALLBACK_LEVEL = {
"DL3000": "error", "DL3002": "warning", "DL3006": "warning",
"DL3007": "warning", "DL3008": "warning", "DL3009": "info",
"DL3015": "info", "DL3020": "error", "DL4000": "error",
"SC2086": "info",
}
ALIASES = {"warn": "warning", "err": "error", "failure": "error", "hint": "info"}
def norm_level(value):
level = str(value or "").strip().lower()
level = ALIASES.get(level, level)
return level if level in RANK else None
fail_on = norm_level(os.environ.get("FAIL_ON_LEVEL")) or "info"
report_path = "hadolint-report.json"
findings = []
parse_error = ""
if not os.path.exists(report_path):
parse_error = "hadolint report file is missing"
elif os.path.getsize(report_path) == 0:
parse_error = "hadolint report file is empty"
else:
with open(report_path, "r") as handle:
raw = handle.read()
try:
doc = json.loads(raw)
except ValueError as exc:
parse_error = "hadolint report is not valid JSON (%s)" % exc
else:
if isinstance(doc, dict):
doc = doc.get("findings") or doc.get("results") or []
if not isinstance(doc, list):
parse_error = "hadolint report is neither a JSON array nor an object with a findings list"
elif any(not isinstance(entry, dict) for entry in doc):
parse_error = "hadolint report contains entries that are not objects"
else:
findings = doc
counts = {"style": 0, "info": 0, "warning": 0, "error": 0}
rule_codes = []
for entry in findings:
code = str(entry.get("code") or entry.get("rule") or "UNKNOWN")
level = (norm_level(entry.get("level"))
or norm_level(entry.get("severity"))
or FALLBACK_LEVEL.get(code, "info"))
counts[level] += 1
if code not in rule_codes:
rule_codes.append(code)
threshold = RANK[fail_on]
over_threshold = sum(count for level, count in counts.items() if RANK[level] >= threshold)
if parse_error:
verdict = "SCAN_ERROR"
elif over_threshold > 0:
verdict = "FAIL"
else:
verdict = "PASS"
pull_request = os.environ.get("PULL_REQUEST", "")
payload = {"outputs": {
"verdict": verdict,
"error_count": counts["error"],
"warning_count": counts["warning"],
"info_count": counts["info"] + counts["style"],
"total_findings": len(findings),
"rule_codes": sorted(rule_codes),
"fail_on_level": fail_on,
"parse_error": parse_error,
"repository": os.environ.get("GITHUB_REPOSITORY", ""),
"pull_request": pull_request,
}}
print("hadolint %s for PR %s with %d finding(s) at fail level %s" % (
verdict, pull_request, len(findings), fail_on))
print("::" + json.dumps(payload) + "::")
# --- 2. severity gate and escalation ---
- id: gate_on_severity
type: io.kestra.plugin.core.flow.If
description: Escalate any Dockerfile whose findings reach the fail level or
whose report could not be parsed, and record the all-clear otherwise.
condition: "{{ outputs.parse_report.vars.verdict != 'PASS' }}"
then:
- id: open_dockerfile_issue
type: io.kestra.plugin.github.issues.Create
description: Open a labeled issue carrying the counts and every rule code so the
fix lands in the backlog the team already works.
jwtToken: "{{ secret('GITHUB_TOKEN') }}"
repository: "{{ inputs.github_repository }}"
title: "hadolint gate failed for PR #{{ inputs.pull_request }}"
body: |
## hadolint Dockerfile policy gate
Pull request **#{{ inputs.pull_request }}** in `{{ inputs.github_repository }}` lints as **{{ outputs.parse_report.vars.verdict }}** at fail level `{{ inputs.fail_on_level }}`.
Counts: **{{ outputs.parse_report.vars.error_count }} error**, **{{ outputs.parse_report.vars.warning_count }} warning**, **{{ outputs.parse_report.vars.info_count }} info/style** findings out of {{ outputs.parse_report.vars.total_findings }}.
Rule codes hit: `{{ outputs.parse_report.vars.rule_codes | toJson }}`
Raw report: `{{ outputs.run_hadolint.outputFiles['hadolint-report.json'] }}`
Execution {{ execution.id }}
Pin the base image tag, pin the apt packages, swap ADD for COPY, drop MAINTAINER, run the final stage as a non-root user, then close this issue once hadolint reports clean.
labels:
- dockerfile
- hadolint
- policy-gate
- id: alert_slack
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Tell the platform channel which verdict the gate reached and how
many errors the Dockerfile carries.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": "Dockerfile gate {{ outputs.parse_report.vars.verdict }} for PR #{{ inputs.pull_request }} in {{ inputs.github_repository }} - {{ outputs.parse_report.vars.error_count }} error, {{ outputs.parse_report.vars.warning_count }} warning, {{ outputs.parse_report.vars.info_count }} info/style finding(s) at fail level {{ inputs.fail_on_level }}. An issue is waiting in {{ inputs.github_repository }}. Execution {{ execution.id }}."
}
else:
- id: log_clean
type: io.kestra.plugin.core.log.Log
description: Record the clean lint so the execution history doubles as merge
evidence.
message: "hadolint clean for PR #{{ inputs.pull_request }} in {{
inputs.github_repository }} at fail level {{ inputs.fail_on_level }}."
errors:
- id: notify_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Escalate any failure to the ops channel with the execution url.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text": "FAILED: {{ flow.id }} {{ execution.id }}"}
outputs:
- id: verdict
type: STRING
value: "{{ outputs.parse_report.vars.verdict }}"
- id: error_count
type: INT
value: "{{ outputs.parse_report.vars.error_count }}"
- id: warning_count
type: INT
value: "{{ outputs.parse_report.vars.warning_count }}"
- id: rule_codes
type: ARRAY
value: "{{ outputs.parse_report.vars.rule_codes | toJson }}"
- id: report_uri
type: STRING
value: "{{ outputs.run_hadolint.outputFiles['hadolint-report.json'] }}"