Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
OPA Rego Conftest and GitHub Actions
# Here is the basic Rego rule
package main
# deny creating duplicate resource in the same namespace
deny_duplicate_resources[{"msg": msg, "details": details}] {
i != j
currentFilePath = input[i].path
input[i].contents.kind == input[j].contents.kind
input[i].contents.metadata.name == input[j].contents.metadata.name
msg := sprintf("no duplicate resources are allowed, file: %q, name: %q, kind: %q, file with duplicate: %q", [currentFilePath, input[i].contents.metadata.name, input[i].contents.kind, input[j].path])
details := {
"file": currentFilePath,
"line": 1,
"url": "http://some.docs.link.here.something/rulex.md",
}
}
# This runs the rule against the yaml with conftest
# Run this inside your GitHub Action
conftest test -p ./rules ./yaml --combine --no-fail -o json | jq -r -f ./convert.jq
# Get all the failure items from the conftest json output
# see: https://www.conftest.dev/options/#json
# Note as we use `--combine` with conftest we will always receive and array consisting of a single item
# To add newlines to the message '\n' has to be urlencoded to %0A
# We split the 'msg' returned by the rule with ','s replaced with newlines
# and also put the doc url on a newline
# see: https://github.com/actions/toolkit/issues/193
try .[0].failures[]
# pull out the file and msg that we care about based on the defined
# test output format
# see: ../README.md#writing-rules
| { "file": .metadata.details.file, "msg": (.msg | gsub(", "; "%0A ")), "url": .metadata.details.url}
# Format that into the structure actions wants
# see: https://docs.github.com/en/actions/learn-github-actions/workflow-commands-for-github-actions#setting-a-warning-message
| "::warning file=\(.file),line=1::\(.msg)%0A%0AAbout this rule: \(.url)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment