What is policy as code?
BeginnerConceptSecurity basics for DevOps
Answer
In one line: Policy as code means writing your security, compliance and operational rules as code that can be automatically checked — in pipelines and in clusters — instead of in documents that people may or may not follow.
Examples of policies:
- All S3 buckets must be encrypted and not public.
- Kubernetes containers must not run as root and must have resource limits.
- Only images from our approved registry are allowed.
- Every cloud resource must have
ownerandcost-centretags. - Only certain instance types and regions can be used.
Tools:
- Open Policy Agent (OPA) with the Rego language — general-purpose; Conftest runs OPA policies on config files in CI; Gatekeeper enforces them in Kubernetes.
- Kyverno — Kubernetes-native policies written in YAML.
- Checkov, tfsec/Trivy, KICS — ready-made IaC security policies, plus custom rules.
- HashiCorp Sentinel — policies for Terraform Cloud/Enterprise.
- Cloud-native: AWS Service Control Policies and Config rules, Azure Policy, GCP Organization Policies.
Where policies are enforced:
- In the pipeline (shift left) — scan Terraform plans and Kubernetes YAML in pull requests.
- At admission time — Kubernetes admission controllers reject non-compliant resources.
- In the cloud account — guardrails that block or flag bad configurations even if someone uses the console.
Example Kyverno policy:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata: { name: require-limits }
spec:
validationFailureAction: Enforce
rules:
- name: check-limits
match: { any: [{ resources: { kinds: [Pod] } }] }
validate:
message: "CPU and memory limits are required."
pattern:
spec:
containers:
- resources:
limits: { memory: "?*", cpu: "?*" }
Benefits: consistent, automatic enforcement; version-controlled and reviewed rules; fast feedback for developers; audit evidence for compliance.
Tip for interviews: mention the "audit first, then enforce" rollout — start in warning mode, fix existing violations, then block.
More on Security basics for DevOps
What is the principle of least privilege?BeginnerWhat is SAST, DAST and SCA?BeginnerWhat is a CVE, and how do you handle vulnerabilities found by scanners?BeginnerWhat is container image scanning, and where should it happen?BeginnerWhat is software supply chain security (SBOM, image signing, SLSA)?IntermediateWhat is secrets management, and why shouldn't secrets be in code?Beginner