Skip to content

Instantly share code, notes, and snippets.

@lawrencegripper
Created January 13, 2020 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lawrencegripper/b2603df6267334e6752d25d2eb2eb228 to your computer and use it in GitHub Desktop.
Save lawrencegripper/b2603df6267334e6752d25d2eb2eb228 to your computer and use it in GitHub Desktop.
blog opa part1
# The top level response sent to the webrequest
main = {
"apiVersion": "admission.k8s.io/v1beta1",
"kind": "AdmissionReview",
"response": response,
}
# If the conditions on the `response` below aren't met this default `allow` response
# is returned.
default response = {"allowed": true }
# This is the response body sent back to admissions controller request
# it starts with a number of conditions which have to be met for it to take effect
#
# Note: output is the return item, inside the body the `output :=` sets this so that response equals
# the value of the `output` object defined in this body.
response = output {
# Retrun this if request is:
#
# A pod
isPod
# Without any pre-existing selectors
not hasNodeSelector
# And in a namespace we care about
shouldProcessForNamespace(ignoredNamespaces)
# Generate the JSON Patch object
patch := {
"op": "add",
"path": "spec/nodeSelector",
"value": {
# Retrieve the `pool` name which should be applied given the
# namespace in which this pod is created.
"agentpool": getPoolForNamespace(input.request.object.metadata.namespace)
}
}
# Patches have to be an array of base64 encoded JSON Patches so lets
# make our single patch into an array, serialize as JSON and base64 encode.
patches := [patch]
patchEncoded := base64.encode(json.marshal(patches))
# Output a trace use `opa test *.rego -v --explain full` to see them.
trace(sprintf("POLICY:generatedPatch raw = '%s'", [patches]))
trace(sprintf("POLICY:generatedPatch encoded = '%s'", [patchEncoded]))
# Generate the patch response and return it! We're done!
output := {
"allowed": true,
"patchType": "JSONPatch",
"patch": patchEncoded
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment