Policy as code
You will learn to encode security and compliance guardrails as executable policy — Rego and Kyverno rules, admission controllers, and IaC gates that block a bad change in the pipeline. Interviewers probe it because it is how a DevSecOps team stops a non-compliant deploy without a human in the loop.
on this pageshowhide
guide
overview
~1 minPolicy as code means writing security and compliance guardrails as rules a machine evaluates, so a non-conforming change is stopped or flagged by the delivery system itself rather than by a reviewer who happened to look. Interviewers use the subject to test two skills together: whether you can write a rule that is actually correct, and whether you understand where it runs, what it can see from that position, and what happens when it is wrong, slow or unreachable. A well-written rule placed where half the changes never reach it is a weak answer, and so is a well-placed rule nobody can debug when it blocks a release. The hub falls into three groups. The foundation is [policy engine fundamentals](/topics/sec-policy-as-code-fundamentals): keeping the decision apart from its enforcement, the points along delivery where a decision can be taken, and the modes a rule can run in. The middle group is the engines and their surfaces: the [Rego language](/topics/sec-policy-as-code-rego), [OPA and Gatekeeper](/topics/sec-policy-as-code-opa-gatekeeper), the [Kubernetes admission control](/topics/sec-policy-as-code-k8s-admission) contract that in-cluster engines sit on, [Kyverno](/topics/sec-policy-as-code-kyverno), and [IaC policy gates](/topics/sec-policy-as-code-iac-gates) over Terraform plans and rendered manifests. The last group is about running a policy programme rather than writing one rule: [compliance as code](/topics/sec-policy-as-code-compliance), [the life of a rule](/topics/sec-policy-as-code-lifecycle-operations) as maintained software, and [blocking a bad change](/topics/sec-policy-as-code-pipeline-gates), where gates meet deadlines, exceptions and bypasses. Start with the fundamentals, since every tool section assumes their vocabulary. Learn Rego next, because it is the language behind OPA, Gatekeeper and conftest, then the admission contract before either in-cluster engine. Questions run from a junior asked to tell two modes apart to a principal asked how a whole organisation should own, ship and suspend its rules; several ideas, missing evidence above all, return at every depth.
primer
A few ideas hold the whole subject together. With them in place, most questions below read as applications rather than trivia. - **Deciding and enforcing are different jobs.** A policy engine evaluates a rule and returns an answer; some other component, such as an API server, a CI job, a deploy tool or a proxy, asks the question and acts on the reply. That split is what lets one rule run at several points, and it puts a hard question on the enforcing side: what to do when no answer arrives in time. - **A rule sees only the document it is handed.** Each decision point passes a particular shape (a plan, a rendered manifest, an admission request, a scan report), and any fact outside that shape, from an approved list to the state of the rest of the cluster, has to be supplied some other way. Many "why did the rule not fire" stories are a missing fact or a field the rule read at the wrong path. - **Placement decides coverage.** A check governs only the changes that travel through it. Early points give fast, cheap feedback on source; later points see the final object; a guardrail built into the cloud provider's own API sees every route, console included. Preventive checks stop a change, detective ones find what already exists, and a serious programme needs both. - **Absence is an outcome, not a pass.** Undefined results, unknown plan values, skipped controls, missing reports and fields that are simply not there all appear in this hub. A rule or gate has to say explicitly which way each kind of silence falls, which is why deny-by-default is the usual stance. - **A rule is software with a blast radius.** One faulty rule can block every team at once, so rules need tests that include changes that must pass, versions consumers can pin, owners, and a staged rollout from audit through warn to enforce. - **A gate is as strong as its exception path.** Waivers, exemptions and break-glass overrides are part of the design, not a failure of it. A gate without a sanctioned, recorded way through is a gate people learn to route around.
- Policy decision point
- The component that evaluates rules against a document and returns an answer, without itself allowing or stopping anything.
- Policy enforcement point
- The component that requests a decision and acts on it: an API server, a CI job, a deploy tool or a proxy.
- Preventive control
- A check that runs before a change takes effect and can stop it, so the bad state is never created.
- Detective control
- A check over state that already exists; it reports violations but cannot stop the change that caused them.
- Audit, warn and enforce
- Three consequences for one rule: record the violation, tell the requester but let the change through, or refuse the change.
- Input document
- In Rego, the document a caller supplies with one query: the change, request or artifact being judged.
- Data document
- In Rego, the standing facts and rule-defined values the engine already holds, read by every query.
- Deny-by-default
- The stance that a request passes only when rules positively allow it, so a missing fact or undefined result cannot quietly approve a change.
- Policy bundle
- A packaged archive of rules and data that an OPA instance downloads and activates, carrying a revision label.
- Admission webhook
- An HTTP callback the Kubernetes API server calls during a write so an external engine can reject or patch the object before it is stored.
- ConstraintTemplate
- Gatekeeper's reusable rule definition with a parameter schema; each Constraint created from it switches the rule on with its own scope and values.
- Background scan
- Evaluation of rules over objects already stored, producing reports instead of blocking writes; the way admission engines see existing state.
- Plan JSON
- The machine-readable form of a Terraform plan that IaC policy tools evaluate before anything is applied.
- Fail open, fail closed
- What an enforcement point does when no decision arrives: let the change proceed, or refuse it.
- Waiver
- A recorded, approved, expiring exception that lets a named resource violate a named rule for a stated reason.
- Break-glass override
- A pre-authorised, conspicuous way to push one blocked change through in an emergency, leaving a record behind.
- Shadow run
- Evaluating a candidate rule against real past changes without blocking anything, to measure what it would have stopped.
- Decision log
- The record an engine emits per decision, typically the input, the result and the policy revision, used for debugging and audit.
The sections line up along the path a change travels, with a programme layer wrapped around them. ### Along the delivery path A change starts as source in an editor and pull request, where [IaC policy gates](/topics/sec-policy-as-code-iac-gates) judge Terraform plans, rendered charts and other configuration before anything exists. It is then built and promoted, and [blocking a bad change](/topics/sec-policy-as-code-pipeline-gates) covers gates at those points, which mostly decide on evidence other tools produced: scan reports, attestations, catalog metadata. At the cluster boundary, [Kubernetes admission control](/topics/sec-policy-as-code-k8s-admission) is the contract every in-cluster engine plugs into, and both [OPA and Gatekeeper](/topics/sec-policy-as-code-opa-gatekeeper) and [Kyverno](/topics/sec-policy-as-code-kyverno) are ways of writing rules against it. After admission, background scans and [compliance as code](/topics/sec-policy-as-code-compliance) look at what is actually running, which catches drift and resources no change ever touched. ### Languages and engines [Rego](/topics/sec-policy-as-code-rego) is a language; OPA is the engine that evaluates it, embedded as a library, beside a service or as a shared server. Gatekeeper packages OPA for Kubernetes, and conftest applies Rego to files in a pipeline, so one rule style can follow a change from pull request to cluster. Kyverno takes the other route: rules are Kubernetes resources written in the platform's own vocabulary, with little separate language to learn and the cluster as their natural home. Sentinel and Checkov occupy the IaC position with their own rule formats. ### The programme layer [Policy engine fundamentals](/topics/sec-policy-as-code-fundamentals) supply the questions every section answers again: where the decision is taken, in which mode, and what happens on silence. [The life of a rule](/topics/sec-policy-as-code-lifecycle-operations) governs every rule in every engine above, from its first test to its retirement. Compliance consumes the decisions as evidence, and pipeline gates decide who may override them.
- Policy Engine Fundamentals →
Decision versus enforcement, decision points and modes are the vocabulary every tool section assumes, so learn them before any engine.
- Rego Language →
The rule language behind OPA, Gatekeeper and conftest; its handling of undefined results explains many surprising verdicts.
- Kubernetes Admission Control →
The API server contract both in-cluster engines plug into: what a request carries, what it lacks, and where interception stops.
- IaC Policy Gates →
Moves the same thinking earlier, onto plans and rendered manifests, where most public-bucket style questions are set.
- The Life of a Rule →
Once you can write a rule, learn to test, version, roll out and own it so it survives contact with real teams.
- Blocking a Bad Change →
Closes the loop: who holds authority over a gate, how it treats missing evidence, and how it bends under deadline pressure.
Treating silence as approval: an undefined result, a skipped control or a missing scan report counted as a pass instead of being handled explicitly.
Assuming a CI check governs the cloud account, when console sessions and local applies never pass through the pipeline at all.
Expecting a new admission rule to bring existing objects into line; it judges writes, so stored objects need a background scan.
Filtering a plan rule on the create action only, so in-place updates that weaken an existing resource slip past unchecked.
Testing only the inputs a rule must refuse; without near-miss allow cases, a rule that rejects everything still passes its suite.
Switching a new rule straight to enforce with no audit or warn period and no shadow run against real changes.
Picking fail-open or fail-closed as a global default instead of per rule, from what an unassessed change versus a halted deploy would cost.
Returning a bare denial with no rule id, field or suggested fix, which turns every block into a support ticket for the policy team.
Scoping a rule to Pods or to human requesters and forgetting that controllers create Pods from templates under their own identity.
Writing Rego in the older v0 syntax for an engine running with v1 defaults, and reading the parse error as a policy failure.
Granting waivers with no owner or expiry date, so temporary exceptions quietly become the permanent policy.
The same few choices come back across nearly every section; naming the one you are making is usually worth more than the rule itself. - **Early versus late placement.** Editor and pull-request checks are fast and cheap to fix but see source that may still be templated; admission and runtime see the final object but fail later and cost more. Mature setups run one rule at several points rather than choosing. - **Fail open versus fail closed.** Open keeps delivery moving but admits changes nobody assessed; closed keeps the guardrail intact but can stop every deploy while the engine is down. The answer differs per rule, by what a missed violation would cost. - **Reject versus mutate.** Patching a missing default is friendly and invisible; patching anything the workload depends on hides a real change from its owner. Reject when the fix alters behaviour. - **General-purpose versus platform-native rules.** A Rego estate spans pipelines, services and clusters with one language; Kyverno-style resources are easier for platform teams to read but are mostly confined to Kubernetes. - **Strictness versus adoption.** A low severity threshold blocks more risk and more noise; a gate that fails too often stops being trusted. Tune blocking rules for precision and send the rest to warn or report. - **Central library versus team ownership.** A central rule set is consistent but slow to change; team-owned rules move fast and drift apart. Versioned, pinned releases are the usual middle ground.
Several shapes recur under different names across the engines; spotting them makes an unfamiliar tool readable quickly. - **A set of violation messages.** Rules add one message per problem found, and an empty set means pass. Rego deny rules, Gatekeeper violations and conftest results all work this way, which is why a good rule reports every problem rather than the first. - **Template plus instance.** A reusable rule with a parameter schema, switched on many times with different scope and values: ConstraintTemplates and Constraints, shared rule libraries with per-team configuration. - **Staged rollout.** Audit, then warn, then enforce, with a shadow run before the first step, so a rule's false-positive rate is known before it can block anyone. - **Defence in depth across points.** The same intent checked at pull request, admission and background scan, each catching what the others cannot see. - **Exception as data.** Waivers and exemptions stored as reviewed, expiring records the engine reads, instead of edits to the rule. - **Decision as evidence.** Every verdict recorded with rule version, input and time, so a later audit or incident can replay why a change passed.
explore
- Policy Engine Fundamentals39 questions
- Decision Model15 questions
- Enforcement Points and Modes13 questions
- Acting on the Answer11 questions
- Rego Language43 questions
- How a Rule Resolves14 questions
- Rules Over Real Input19 questions
- Proving the Rule10 questions
- OPA & Gatekeeper45 questions
- Running the Engine11 questions
- Feeding the Engine11 questions
- Rules as Cluster Objects23 questions
- Kubernetes Admission Control42 questions
- The Intercepted Request18 questions
- Writing Rules In-Cluster12 questions
- Limits of Interception12 questions
- Kyverno41 questions
- Matching and Deciding25 questions
- Changing and Creating8 questions
- When It Does Not Block8 questions
- IaC Policy Gates37 questions
- Artifact Under Evaluation17 questions
- Custom Rule Authoring12 questions
- Enforcement Decisions8 questions
- Compliance as Code36 questions
- Control to Check12 questions
- Assessing Live Systems12 questions
- Evidence and Exceptions12 questions
- The Life of a Rule44 questions
- Writing a Testable Rule12 questions
- Owning and Shipping Rules16 questions
- Rules in Production16 questions
- Blocking a Bad Change36 questions
- Reports and Attestations11 questions
- Placement and Authority14 questions
- When the Gate Bends11 questions
questions
363 · 9 sectionsIn a policy decision, what separates the change under evaluation from the surrounding facts?
basics
~20 sThe change under evaluation is the document being decided on, such as a proposed plan or manifest. The surrounding facts are everything else the rule needs, like the list of approved instance types, which the change never carries.
What do PDP, PEP and PIP each do in a policy-as-code gate?
basics
~20 sA policy decision point evaluates the rule and returns an answer. A policy enforcement point sits in the change's path, gathers the input, asks, and acts on the reply. A policy information point supplies facts the change itself does not carry.
A CI job enforces backup retention with a shell script that exits 1. What does restating it as a policy rule buy?
basics
~20 sA rule file states the condition as data, so the engine can report which rule failed on which resource, and the same rule can be listed, reviewed and reused elsewhere. An exit code carries one bit: pass or fail.
A policy gate blocks your deploy with only 'denied by policy' — what should that denial have carried?
basics
~20 sA usable denial names the rule that fired, the object and the exact field it failed on, what the rule requires, and one concrete fix. It should list every violation found, not only the first.
A deploy tool calls a policy decision service and gets no answer - what do fail-open and fail-closed mean here?
basics
~20 sFail open means the deploy proceeds when the decision service cannot answer; fail closed means it is rejected. Open protects delivery and lets unassessed changes through; closed protects the guardrail and can halt every deploy in the organisation.
In Rego, what does a deny rule written as a partial set of messages produce when no input violates it?
basics
~10 sIt produces the empty set. Each successful evaluation of the rule body adds one message; when nothing matches, there are zero messages, and a runner such as conftest reports that as a pass.
In Rego, where does a rule get a fact that the artifact under evaluation does not contain?
basics
~20 sA Rego rule cannot invent a fact. It must be loaded into the engine before the query, supplied by the caller inside the query itself, or fetched during evaluation with http.send. Nothing else reaches a rule.
Why does a Rego rule written as deny[msg] { ... } fail to parse under OPA v1?
basics
~20 sOPA v1 makes if and contains mandatory, so a partial set rule must read deny contains msg if { ... }. The bare v0 head is a parse error, not a deprecation. import rego.v1 opts a single file into v1 syntax on an older engine.
In Rego, what is the difference between the input document and the data document?
basics
~20 sinput is the document the caller sends with a single query, the thing being judged. data is the tree the engine already holds: JSON loaded alongside the policy, plus the virtual documents that rules themselves define.
In Rego, what is the difference between an expression that is undefined and one that is false?
basics
~20 sFalse is a value; undefined means Rego found no value at all. Both stop a rule body, but false is an answer, while undefined leaves the rule with no result to emit and no error to report.
What does an OPA bundle contain, and what is the revision in its .manifest for?
basics
~20 sAn OPA bundle is a gzipped tar archive of Rego policy, data files and an optional .manifest. The manifest's revision is an opaque label for that build, reported in OPA's status and decision output so you know which policy decided.
What is OPA's data document, and what are the ways facts get loaded into it?
basics
~20 sOPA's data document is the in-memory JSON tree of standing facts policies read as data.something, separate from the input being decided. Facts arrive as startup files, inside a bundle OPA polls for, or as pushes to its Data API.
What does Gatekeeper's audit controller do, and where does it write what it finds?
basics
~20 sGatekeeper's audit controller periodically re-evaluates objects that already exist in the cluster against every enforced Constraint and records the violations in each Constraint object's own status field. It only reports: it never blocks, deletes or changes anything.
What does Gatekeeper's gator test command evaluate, and what must you feed it?
basics
~20 sgator test evaluates Gatekeeper policy locally: you hand it ConstraintTemplates, their Constraints, and the Kubernetes objects to review, and it reports which object violated which constraint. It needs no cluster, no kubeconfig and no admission webhook.
What does a Gatekeeper Assign resource do, and how does it differ from a Constraint?
basics
~10 sA Gatekeeper Assign is a mutator: at admission it writes a value into a field of the incoming object, so the object is stored changed instead of rejected. A Constraint only inspects and denies.
When you kubectl apply a Deployment, which admission requests does the API server actually see?
basics
~20 sThree separate ones, not one: your Deployment, then the ReplicaSet the deployment controller creates, then one request per Pod from the ReplicaSet controller. Each is admitted on its own, under the controller's identity rather than yours.
In Kubernetes, kubectl printed a 'Warning:' line and still created the object - what happened at admission?
basics
~20 sA warning is advisory only. The API server returned it in an HTTP Warning response header alongside a response that succeeded, so the object was admitted. Only a denial, which comes back as a failed status, stops the write.
Why do cluster-wide Kubernetes admission policies exclude kube-system from their match scope?
basics
~20 sThe rule was written for tenant workloads, not cluster infrastructure — and the policy engine's own Pods live in a system namespace, so an engine inside its own scope can block the Pods that would replace it.
What does a Kubernetes AdmissionReview request contain, and what cluster information is missing from it?
basics
~20 sAn AdmissionReview request carries one object under review, its previous version on updates, the requesting user and groups, the operation, resource and subresource, and a dryRun flag. It carries no other objects, no cluster state and no history.
When should an admission policy reject a Kubernetes manifest instead of silently patching it?
basics
~20 sPatch when the fix is behaviour-neutral and the platform owns the value, like adding a missing default. Reject when the compliant form changes what the process sees, such as moving a secret from an environment variable into a mounted file.
What does the Kyverno CLI command kyverno apply do with a policy and a manifest file?
basics
~20 skyverno apply reads policy files and resource files from disk and evaluates the rules against them locally, printing pass, fail, skip and warn results. It is a dry run: no cluster is contacted and nothing is admitted.
What does a Kyverno PolicyException name, and what does it not switch off?
basics
~20 sA Kyverno PolicyException names the policy and the specific rule names it waives, plus a match block selecting which resources the waiver covers. It never disables the policy itself; anything the match block misses is still enforced.
What does a Kyverno generate rule do that a validate rule cannot?
basics
~20 sA Kyverno generate rule creates a companion object when a trigger appears, such as a default-deny NetworkPolicy in every new namespace. A validate rule can only accept or reject the request; generate supplies the resource instead of demanding it.
In a Kyverno mutate rule, what does the +() add-if-not-present anchor do?
basics
~20 sThe +() anchor in a Kyverno strategic-merge mutate patch sets a field only when the incoming object does not already have it. If the field is already present, the existing value is left alone rather than overwritten.
In Kyverno, what does a validate.deny conditions block do that validate.pattern cannot?
basics
~20 sA deny block evaluates boolean conditions with operators over the admission request and blocks when they are true. A pattern only asserts the shape a resource must match, so it cannot use operators, compare two fields, or read request metadata.
In a Terraform plan JSON, which section shows that one resource references another?
basics
~10 sThe configuration section. Each resource there carries an expressions object whose references list the addresses it points at. The planned_values section holds only each resource's resolved attribute values and records no links between resources.
In a Terraform plan JSON, where do resources declared inside a module appear to a policy rule?
basics
~20 sThe plan is flattened. Every resource a module declares is expanded into the plan's resource lists under a module-qualified address such as module.network.aws_s3_bucket.flow_logs, so ordinary resource rules fire on module-created resources without knowing modules exist.
Why must a Helm chart be rendered before conftest can evaluate its Kubernetes manifests?
basics
~10 sA chart's templates are Go template text, not valid YAML, and fields hidden behind conditionals only appear once values are applied. Render the chart first, then evaluate the manifests it produces.
In a Terraform plan JSON, how do `planned_values` and `resource_changes` differ for a policy rule?
basics
~20 splanned_values is the whole post-apply state, every managed resource including untouched ones. resource_changes is the per-resource diff, carrying the action and the before and after values. A rule over planned_values judges the estate; a rule over resource_changes judges this run.
In a Terraform plan, what does an attribute marked "known after apply" mean for a policy rule?
basics
~20 sIt means the value does not exist yet: the provider or cloud only produces it when the resource is actually created, so the plan holds a placeholder. A policy rule evaluating that attribute has nothing real to test.
Why map one TLS-minimum check to clauses in three compliance frameworks instead of writing three checks?
basics
~10 sThe check is the same engineering fact; only the reporting differs. One check with three mapping edges means one rule to maintain and three audit reports that can never disagree about the same listener.
What does it mean to decompose a compliance control into automated checks?
basics
~20 sDecomposition turns one control sentence into the separate facts a machine can test. "Audit logging enabled and retained 365 days" becomes distinct checks: a log destination exists, retention is at least 365, tamper-evidence is on, delivery still succeeds.
A control report says 98% of database instances are encrypted at rest — what does that number hide?
basics
~20 sA pass rate hides its denominator. The 98% counts only instances the check actually enumerated; anything in an account, region or project the tooling never reached sits outside both numbers, so unseen systems are invisible rather than failing.
Your 90-day password rotation check passes on every account — what risk does it not cover?
basics
~20 sIt proves only that passwords change on schedule. It says nothing about phishing, stolen session tokens, or accounts that were never removed. A green control measures the activity someone wrote down, not the attack it was meant to stop.
What must an automated backup-retention check record so its result works as audit evidence later?
basics
~20 sEach record needs the verdict plus everything that makes it re-checkable: which control it proves, which resource was evaluated, the exact rule version and input it saw, when it ran, and which identity ran it.
What is a shadow run of a candidate policy rule, and what does it tell you before you enforce it?
basics
~20 sA shadow run evaluates a candidate rule offline against a corpus of real, already-completed changes and records the verdict it would have given each one, without blocking anything. It shows how often the rule fires and on what.
Why does a policy rule's test suite need near-miss allow cases, not just deny cases?
basics
~10 sNear-miss cases are legitimate inputs sitting just inside the boundary — the changes the rule must let through. Deny cases only prove a rule can refuse something. They never prove it refuses nothing else.
What is a policy rule's input contract, and what does it pin down?
basics
~10 sThe input contract is the written agreement about the document a rule decides over: which step produces it, how it is wrapped, and which fields are guaranteed present. Agree it before writing the rule.
Your nightly encryption-at-rest sweep reports zero violations — what must you know before that means anything?
basics
~20 sWhich ruleset produced the number and what it covered. Zero violations only means the rules that actually loaded found nothing in the resources that were actually enumerated. An empty or replaced ruleset reports exactly the same green.
Why is a policy rule repository reviewed, tested and released like application code?
basics
~20 sA rule is production code: one bad rule blocks every team's builds at once. Review, tests and CI catch it before it reaches a gate, and give each change an author, a reviewer and a history.
What is a break-glass override of a blocking policy gate, and what must it leave behind?
basics
~20 sA break-glass override is a pre-authorised, deliberately loud way to ship one change that a policy gate denied, used when waiting is worse than the risk. It must leave a record: who pulled it, which rule, which change, and why.
A CI check rejects plans requesting a disallowed instance type, so why do such instances still appear in the account?
basics
~20 sA CI check only sees changes that travel through CI. Anyone holding cloud credentials can create the instance from a console session or a local apply, and that route never reaches the check at all.
Why is a pull-request policy check advisory when an in-cluster reconciler is the only thing that applies manifests?
basics
~20 sMerging is not deploying. The reconciler reads whatever sits on the tracked branch and applies it, without consulting the check that ran on the pull request. The check informs humans; it has no authority over the applier.
In a pull request, what is a required check, and what happens if it never reports a result?
basics
~20 sA required check must report a passing result before the pull request may merge. An advisory check only posts a result nobody consults. If a required check never reports, the merge stays blocked rather than allowed.
A build gate finds no vulnerability scan report attached to an artifact — is that a pass?
basics
~20 sNo. A missing report is not a clean result, it is an absent one. A gate needs three outcomes — pass, fail, and no usable evidence — and the third must never be folded silently into the first.