Infrastructure and securityIntermediate40 min read

What Is Policy as code? Security Definition

Reviewed byJohnson Ajibi· Senior Network & Security Engineer · MSc IT Security
On This Page

Quick Definition

Policy as code means writing your organization's rules as computer code instead of keeping them in a document. This code can be automatically checked every time you make a change to your systems, ensuring you never accidentally break a rule. It helps teams move faster without compromising on security or compliance, because the rules are enforced by machines, not manual reviews.

Common Commands & Configuration

aws organizations attach-policy --policy-id p-examplepolicy --target-id ou-exampleou

Attaches a Service Control Policy to an organizational unit in AWS Organizations. This restricts permissions for all accounts within that OU.

Tests knowledge of SCP attachment and inheritance in AWS Organizations (SAA, CISSP). Remember that explicit deny at the OU level overrides any allow at the account level.

az policy assignment create --name 'require-encryption' --policy 'audit-storage-encryption' --scope /subscriptions/1234/resourceGroups/prod

Assigns an Azure Policy definition to a specific resource group, auditing storage accounts for encryption. The policy effect is typically Audit or Deny.

Common AZ-104 and SC-900 scenario: assigning policies at different scopes. The scope (management group, subscription, RG) matters for inheritance and compliance.

kubectl apply -f constraint.yaml --namespace gatekeeper-system

Applies a Gatekeeper constraint template and constraint to a Kubernetes cluster. This enforces policies like disallowing privileged containers.

Tests understanding of OPA Gatekeeper admission control (CISSP, CySA+). Constraints are validated against constraint templates written in Rego.

terraform plan -policy-file=policy.sentinel

Runs Terraform plan with a Sentinel policy file to validate infrastructure before deployment. The policy can deny creation of resources that don't meet compliance.

Appears in Terraform Associate and AZ-400 exams. Sentinel policies are evaluated in context, and a violation will output an error message and block the apply.

aws config put-config-rule --config-rule file://s3-public-read-rule.json

Creates a custom AWS Config rule that evaluates S3 buckets for public read access. The rule triggers evaluations and marks resources as compliant or non-compliant.

Frequently tested in AWS SAA and SysOps exams. The rule effect is typically 'Compliance' or 'NonCompliant', and remediation actions may be automated via SSM Automation.

az policy remediation create --name 'encrypt-storage' --policy-assignment 'storage-encryption' --resource-group my-rg

Triggers a remediation task for an Azure Policy assignment that has a 'DeployIfNotExists' effect. It automatically remediates non-compliant resources.

Essential for AZ-104 and AZ-400. Shows understanding of automatic remediation versus manual audit. The remediation task runs on demand or on a schedule.

kyverno apply /path/to/policy.yaml --resource /path/to/resource.yaml

Applies a Kyverno policy to a Kubernetes resource for testing without deploying to a cluster. Validates if the resource would be admitted.

Relevant for Kubernetes security certs and CISSP. Kyverno policies are YAML-based, making them easier to read than Rego. Tests ability to pre-validate before deployment.

opa eval --data policy.rego --input input.json 'data.terraform.deny'

Evaluates a Rego policy against input data using Open Policy Agent CLI. Returns true if the policy denies the action, false otherwise.

Common in CySA+ and advanced security exams. Tests reading of Rego rules. The result 'true' indicates denial, while 'false' means allowed.

Must Know for Exams

Policy as code is a core concept in several certification exams because it represents a modern approach to governance and security automation. For the AWS Solutions Architect Associate (AWS-SAA), you need to understand AWS Organizations Service Control Policies (SCPs) and AWS Config rules as examples of policy as code. Questions often ask how to enforce that all S3 buckets have encryption enabled across an entire AWS organization, and the correct answer involves SCPs or an AWS Config rule with automatic remediation. Similarly, for the Microsoft Azure Administrator (AZ-104) and Azure DevOps (AZ-400) exams, Azure Policy is a primary topic. You will be asked how to assign policies, create custom definitions, and understand the effect of policy evaluation on resource creation. The AZ-400 exam specifically covers integrating policy as code into CI/CD pipelines, such as using Azure Policy in combination with Azure DevOps gates to prevent non-compliant deployments.

For the CompTIA Security+ and CySA+ exams, policy as code appears under domain 3 (implementation) and domain 4 (operations and monitoring). While these exams do not require deep coding of policies, they expect you to know that automated policy enforcement improves security posture and reduces human error. The CISSP exam (ISC2-CISSP) covers policy as code under the asset security and security operations domains. You must understand how policy as code supports automated compliance and audit trails. In the Microsoft 365 exams (MD-102, MS-102, SC-900), policy as code is relevant for understanding how Microsoft’s compliance tools like Microsoft Purview and Intune use policy definitions to enforce security settings across devices and cloud services.

In all these exams, typical question patterns include: “Which tool would you use to enforce a policy that all storage accounts must be encrypted?” or “A developer wants to automatically prevent deployment of non-compliant resources. What is the best approach?” The answer usually involves a policy as code solution like Azure Policy, AWS Config rules, or OPA. You may also see questions about the difference between Azure Policy and Role-Based Access Control (RBAC), or how policy as code complements infrastructure as code. Understanding these nuances is critical for scoring well.

Simple Meaning

Think of policy as code like having a set of traffic laws that are automatically enforced by your car's computer. In the old days, traffic rules were written in a book, and you had to remember them or look them up when you drove. If you made a mistake, a police officer might catch you later. Now imagine your car has a system that knows the speed limit on every road and refuses to let you go over it. It knows which streets are one-way and won't let you enter the wrong direction. It even knows which parking spots are reserved and will only let you park where you’re allowed. That is what policy as code does for your IT systems.

In IT, a “policy” is any rule about how things should be set up or used. For example, a policy might say that all storage buckets must be encrypted, or that only certain people can access a particular database. Traditionally, these rules were written in a PDF or a wiki page, and someone had to manually check whether the rule was being followed. If the person forgot, or if there were hundreds of rules, mistakes happened.

Policy as code changes this by writing the policy in a special language that computers can understand. Now, every time someone tries to create a new storage bucket, the system reads the policy and checks if the bucket meets the encryption rule. If it doesn’t, the system can block the creation or automatically apply encryption. No human has to remember to check the rule. This is a huge shift because it moves from reactive, manual auditing to proactive, automated enforcement.

Another way to understand it is like a recipe that a smart oven follows. The recipe says “bake at 350 degrees for 30 minutes.” If you try to set the oven to 500 degrees, the oven says “That violates the recipe. I will only let you bake at 350.” The recipe is the policy, and the oven enforces it automatically. In IT, the “recipe” is your security and compliance rules, and the “oven” is your infrastructure system that enforces those rules.

This makes life easier for system administrators, developers, and security teams. Developers can focus on building features instead of remembering dozens of security rules. Security teams know that the rules they set are actually being followed, because the code enforces them. And auditors get clear reports showing that the system followed the rules, every single time.

Full Technical Definition

Policy as code is a methodology rooted in the broader discipline of infrastructure as code, where security, compliance, and operational rules are expressed in formal, machine-readable languages and integrated into continuous integration and continuous deployment (CI/CD) pipelines. The core idea is to treat policy definitions with the same rigor as application code: version-controlled, tested, reviewed, and deployed through automated pipelines. This approach ensures that policy enforcement is consistent, auditable, and scalable across diverse environments.

At the technical level, policy as code relies on declarative policy languages such as Open Policy Agent (OPA) with Rego, HashiCorp Sentinel, AWS CloudFormation Guard, or Microsoft Azure Policy with JSON-based policy definitions. These languages allow you to express conditions, constraints, and actions in a structured format. For example, an OPA rule might state that any AWS S3 bucket must have encryption enabled, using a Rego rule that evaluates the bucket’s properties against that requirement. The policy engine evaluates these rules at decision points, such as when an API call is made to create a resource, or as part of a pipeline step that validates infrastructure templates before deployment.

The architecture typically involves a policy engine that runs as a sidecar service, a standalone service, or is embedded directly into a CI/CD tool. When a request to provision a resource is made, the policy engine receives a structured input (often in JSON) describing the request and the current state. The engine evaluates the input against the set of policies and returns a decision: allow, deny, or warn. This decision is then enforced by the calling system. This pattern is known as “decoupled policy decision” and is a key part of the XACML (eXtensible Access Control Markup Language) architecture, though modern implementations are lighter.

Policy as code also integrates with standards like the Policy Core Information Model (PCIM) and is often used alongside compliance frameworks such as CIS Benchmarks, NIST 800-53, or PCI DSS. By encoding these standards as code, organizations can continuously validate their cloud environments against those benchmarks. Tools like AWS Config Rules, Azure Policy, and Google Cloud’s Organization Policies are native implementations of policy as code, allowing you to define rules that are automatically enforced across all resources in a cloud account.

In practice, policy as code is implemented in several layers. At the infrastructure layer, policies control resource configurations such as encryption settings, network rules, and tagging. At the application layer, policies govern access control, data validation, and workflow permissions. At the CI/CD layer, policies gate deployments based on compliance checks, such as ensuring that no container image with critical vulnerabilities is deployed to production. This layered approach ensures that rules are enforced at every stage of the software delivery lifecycle.

Real IT implementations frequently use a combination of open-source and vendor tools. For example, a company might use Terraform with OPA to validate infrastructure-as-code templates before they are applied. The OPA policy checks might include ensuring that all EC2 instances have a specific tag, that security groups don’t allow unrestricted inbound SSH access, and that S3 buckets are not publicly accessible. The Terraform plan is sent to OPA, which evaluates it against the policies and returns a pass or fail. If it fails, the pipeline stops and the developer is notified with a clear message about what rule was violated.

Azure Policy is another robust implementation. In Azure, you can create policy definitions using JSON that evaluate resource properties. For instance, you can create a policy that denies the creation of any virtual machine that is not using a specific size, or that enforces a specific encryption configuration for storage accounts. These policies can be assigned to management groups, subscriptions, or resource groups, and they are evaluated in real time when a resource is created or updated. Azure also provides built-in policy definitions mapped to SOC 2, ISO 27001, and other compliance standards.

Real-Life Example

Imagine you are the manager of a large apartment building. You have rules that every tenant must follow: no loud music after 10 PM, no smoking in common areas, and no BBQs on the balcony. Traditionally, you would print these rules and hand them to each tenant when they move in. You might do occasional patrols, but you wouldn’t catch every violation. Some tenants forget the rules, and others ignore them. You spend a lot of time investigating complaints and issuing warnings.

Now imagine you could install a smart system in the building that automatically enforces these rules. The smart system knows the time, so after 10 PM, it automatically lowers the volume on any speakers in the building. It detects smoke in the common area and immediately turns on ventilation and alerts you. It monitors the balconies and if a BBQ is lit, the gas supply to that balcony is automatically shut off. This smart system is policy as code. You have taken your rules and coded them into the building’s automation system.

In this analogy, the apartment building is your cloud or IT infrastructure. The tenants are developers or users who create and manage resources. The rules are your security and compliance policies. The smart system is the policy engine that evaluates every action. Instead of relying on people to remember the rules, you have written them into the system itself. This means that the rule against balconies being used for BBQs is never forgotten, never ignored, and never bypassed by accident.

This analogy also illustrates the benefits. You can change a rule easily by updating the code. If you decide that quiet hours should start at 11 PM instead of 10 PM, you edit the policy file and the system automatically enforces the new time. You do not have to reprint pamphlets or retrain your tenants. The system also logs every action, so you have a perfect audit trail of who tried to do what and whether it was allowed or denied. If a tenant complains that their BBQ worked fine last week, you can show them the log that their gas was actually shut off three times, but they may not have noticed because the system was so fast.

This mapping is direct: in IT, policy as code enables the same kind of automatic, consistent, auditable enforcement. It turns a manual, error-prone process into an automated, reliable one. For learners, this analogy helps explain why policy as code is not just a buzzword, but a practical necessity for managing complex, fast-paced environments.

Why This Term Matters

In today’s IT environments, teams are deploying changes dozens or even hundreds of times a day. Traditional manual reviews cannot keep up. Policy as code allows organizations to scale their compliance and security efforts without adding human bottlenecks. It ensures that every new resource, configuration change, or deployment is automatically checked against the rules, preventing misconfigurations that could lead to security breaches or compliance failures.

For system administrators, policy as code reduces the cognitive load of remembering every security requirement. Instead of mentally checking a checklist, they can trust that the pipeline will enforce the rules. For security teams, it provides assurance that the policies they design are actually being implemented, because the enforcement is automated and logged. For auditors, it provides clear, machine-readable evidence that controls are in place and working.

policy as code supports a “shift left” approach to security, meaning that issues are caught early in the development cycle, rather than in production. This saves time and money. It also enables organizations to adopt a “deny by default” security posture, where any resource that does not explicitly meet the policy is automatically blocked. This is far more secure than the traditional “permit by default, review later” approach.

How It Appears in Exam Questions

Exam questions about policy as code typically fall into three categories: scenario-based, configuration-based, and troubleshooting. In scenario-based questions, you are given a business requirement, such as “The company wants to ensure that all virtual machines deployed in the development subscription use only approved VM sizes.” You must then choose the best solution, often Azure Policy (with a deny effect) or an AWS Service Control Policy. These questions test whether you can differentiate between a policy that prevents non-compliant resources from being created and a policy that only audits them.

Configuration-based questions present a snippet of a policy definition, often in JSON, and ask what the policy does. For example, an Azure Policy definition might include a condition like “field = ‘type’ equals ‘Microsoft.Compute/virtualMachines’” and an effect of “deny.” The question might ask: “What is the result if a user tries to create a virtual machine with an unapproved size?” You need to interpret the policy and understand that the deployment will be blocked. Alternatively, an AWS Config rule might be written as a Lambda function that checks whether an S3 bucket has versioning enabled. The question might ask how to automatically remediate a non-compliant bucket, and the answer would involve AWS Config auto-remediation.

Troubleshooting questions might describe a situation where a policy is not being enforced as expected. For example, “A company has assigned an Azure Policy to deny the creation of storage accounts without HTTPS traffic. However, a user was still able to create a storage account without HTTPS. What is the most likely cause?” The answer could be that the policy was assigned at a scope that does not include the resource group where the storage account was created, or that the policy was set to “audit” instead of “deny.” These questions test your understanding of policy scope, effect, and evaluation behavior.

In all cases, the exam expects you to know the specific tools and their capabilities, not just the general concept. For example, for AWS exams, know the difference between SCPs (which apply to all accounts in an organization) and IAM policies (which apply to specific users or roles). For Azure exams, know that Azure Policy is separate from RBAC: RBAC controls who can do what, while Azure Policy controls what resources can be created or configured. For CISSP, you might see a question about how policy as code supports the “automated provisioning” control in NIST 800-53.

Practise Policy as code Questions

Test your understanding with exam-style practice questions.

Practise

Example Scenario

A junior cloud engineer at a mid-sized company named TechFlow is tasked with setting up a new AWS environment for a development team. The company has a security policy that no S3 bucket should be publicly accessible. The engineer knows that a lot of teams have accidentally made buckets public in the past, causing data leaks. The traditional approach would be to remind everyone of the policy and hope they remember. But the engineer decides to use policy as code.

They write a policy using AWS CloudFormation Guard that checks if any S3 bucket has a public ACL or a public bucket policy. They integrate this policy into the CI/CD pipeline that the development team uses to deploy their infrastructure. Now, whenever a developer submits a Terraform template to create a new S3 bucket, the pipeline first runs the CloudFormation Guard policy against the template. If the template would create a public bucket, the pipeline fails with a clear error message: “Policy violation: S3 bucket must not be publicly accessible.” The developer has to fix the configuration before the template is even applied.

Later, the engineer also enables AWS Config with a managed rule called “s3-bucket-public-read-prohibited.” This rule continuously evaluates all existing S3 buckets and flags any that are public. If a bucket becomes public due to a configuration change outside the pipeline, AWS Config automatically applies a remediation action, such as removing the public ACL. This layered approach covers both new and existing resources.

The result is that TechFlow no longer has public S3 buckets, even though many changes are made every day. The security team is happy because they know the policy is enforced automatically. The developers are happy because they don’t have to remember the rule; the system guides them. And the audit team can easily prove compliance by looking at the policy and the audit logs.

Common Mistakes

Thinking policy as code is the same as RBAC (Role-Based Access Control).

RBAC controls which users can perform which actions (e.g., who can create a VM). Policy as code controls what configurations those VMs must have (e.g., VM must be a specific size). They serve different purposes and are often used together.

Remember: RBAC = who can do what. Policy as code = what resources must look like.

Believing that a policy set to 'audit' mode will block non-compliant resources.

Audit mode only logs non-compliant resources; it does not prevent them from being created or changed. To block them, you need the 'deny' effect.

Always check the effect of a policy. 'Audit' logs, 'deny' blocks.

Assuming policy as code only applies to cloud infrastructure.

Policy as code can also be applied to application-level decisions, such as validating API requests, checking content of outgoing messages, or enforcing data formatting rules. Open Policy Agent is commonly used for these use cases.

Think of policy as code as a general pattern that can be applied wherever decisions need to be automated.

Ignoring policy scope when assigning policies.

If a policy is assigned only at the subscription level, it will not affect resources in a different subscription. A common exam trap is that a policy is not working because it was assigned at the wrong scope.

Always verify the scope of policy assignment: management group, subscription, or resource group.

Confusing Azure Policy with Azure Blueprints.

Azure Blueprints packages Azure Policy definitions along with other artifacts like RBAC assignments and resource templates. Azure Policy is just one component of Blueprints. They are not interchangeable.

Blueprints are a bundle; Policy is a single piece.

Exam Trap — Don't Get Fooled

{"trap":"An exam question asks: 'A company wants to prevent developers from creating storage accounts without encryption. Which Azure tool should they use?' The options include Azure Policy, RBAC, Azure Blueprints, and Azure Key Vault.

Learners often pick RBAC because they think of 'prevent users from doing something.'","why_learners_choose_it":"Learners confuse 'preventing an action' with 'controlling who can do an action.' RBAC can deny the ability to create storage accounts entirely, but that is too broad.

The requirement is to allow creation but only if encryption is enabled. That is a policy about the resource configuration, not about user permissions.","how_to_avoid_it":"Focus on the keyword 'enforce a configuration requirement.'

If the question says 'ensure that the resource has a specific property,' the answer is almost always Azure Policy (or AWS Config, etc.). RBAC is for access control, not for configuration compliance."

Commonly Confused With

Policy as codevsInfrastructure as Code (IaC)

Infrastructure as code is about writing code to provision and manage infrastructure resources (like VMs, networks, storage). Policy as code is about writing code to define the rules that those resources must follow. IaC creates the resources, policy as code validates and enforces the rules on them. They are complementary.

Terraform is IaC; OPA policies that check Terraform plans are policy as code.

Policy as codevsRole-Based Access Control (RBAC)

RBAC controls which actions a user or service principal can perform on resources. Policy as code controls the configuration of those resources. RBAC might allow a user to create a VM, but policy as code might deny the creation if the VM is not encrypted.

An Azure RBAC role gives a developer 'Contributor' access to a resource group. An Azure Policy then denies the creation of any VM that does not use managed disks.

Policy as codevsCompliance as Code

Compliance as code is a superset that often includes policy as code but also includes automated evidence collection, reporting, and remediation workflows. Policy as code is the specific mechanism for expressing and enforcing rules. Think of compliance as code as the entire program, and policy as code as the engine that drives part of it.

A compliance as code solution might use policy as code to check rules, then automatically generate a compliance report and file a ticket if something fails.

Policy as codevsSecurity as Code

Security as code is a broader philosophy of embedding security practices into every phase of software development and operations. Policy as code is a specific practice within that philosophy, focused on encoding security policies. Security as code includes things like static code analysis, secret scanning, and vulnerability scanning, not just policy enforcement.

Using a tool to scan for hardcoded passwords in code is security as code. Using Azure Policy to enforce that VMs use encrypted disks is policy as code.

Step-by-Step Breakdown

1

Identify the policy requirements

First, determine what rules you need to enforce. This could come from a compliance framework (like PCI DSS), organizational security standards, or operational best practices. For example, 'All storage accounts must have encryption enabled.'

2

Choose the policy tool and language

Select the appropriate tool for your environment. For AWS, you might choose AWS CloudFormation Guard or OPA. For Azure, you use Azure Policy with JSON. For multi-cloud, OPA with Rego is common. The language determines how you express the conditions.

3

Write the policy definition

Translate the natural language rule into the policy language. For example, in Azure Policy JSON, you define a condition like 'field': 'type' equals 'Microsoft.Storage/storageAccounts' and then a condition on the 'supportsHttpsTrafficOnly' property. This step requires understanding the resource schema.

4

Test the policy definition

Before deploying, test the policy in a sandbox environment. Many tools provide a way to simulate policy evaluation against sample data. This catches syntax errors and logic mistakes early.

5

Assign the policy to a scope

Policy must be assigned to a scope where it will be evaluated. In Azure, this can be a management group, subscription, or resource group. The scope determines which resources are subject to the policy. Assigning at a higher scope covers more resources.

6

Choose the policy effect

Decide what happens when the policy condition is not met. Common effects are 'deny' (block the action), 'audit' (log the non-compliance but allow), or 'modify' (automatically change the resource to be compliant). The effect dramatically changes behavior.

7

Integrate into CI/CD pipeline

For pre-deployment enforcement, incorporate the policy evaluation into your CI/CD pipeline. For example, during a Terraform plan step, run the plan through OPA. If the check fails, the pipeline stops, preventing the non-compliant resource from being deployed.

8

Monitor and remediate

Once the policy is active, continuously monitor compliance status. Use tools like AWS Config or Azure Policy Insights to see which resources are non-compliant. Set up automatic remediation actions where possible, such as automatically applying encryption.

9

Update policies iteratively

Policies are not static. As new requirements emerge or new resource types are added, update your policy code. Follow the same version control and testing practices as with any other code.

Practical Mini-Lesson

Policy as code is more than just a theoretical concept; it requires practical skills to implement correctly. Let’s walk through a real-world example using Azure Policy. Imagine you are an Azure administrator at a company that needs to ensure all virtual machines use only approved VM sizes to control costs. The approved sizes are Standard_DS2_v2 and Standard_DS3_v2. You want to deny creation of any VM that uses a different size.

First, you would create a custom Azure Policy definition. The JSON would look something like this: you define a policyRule that checks the ‘type’ field equals ‘Microsoft.Compute/virtualMachines’ and then checks that the ‘properties.hardwareProfile.vmSize’ is not in the list of allowed sizes. The effect would be ‘deny.’ You then assign this policy to the subscription where the development team works. Now, if a developer tries to deploy a VM with size Standard_D4s_v3, the deployment is rejected with a clear error message.

Now, what could go wrong? A common pitfall is that the policy works for new resources but does not affect existing ones. If you want to also flag or remediate existing VMs that are non-compliant, you need a separate initiative or a policy with the ‘modify’ effect. Another pitfall is that the policy might conflict with another policy. For example, if another policy forces all VMs to be of size Standard_D4s_v3, the two policies would conflict and one would take precedence. You need to understand policy precedence rules in Azure: the highest precedence at the most restrictive scope wins.

In a CI/CD context, integrating policy as code means that your pipeline must have access to the policy engine. For AWS, you might use a tool like Bridgecrew or cfn-lint that checks CloudFormation templates against a library of rules. For Terraform, you can use the built-in ‘sentinel’ engine with HashiCorp Cloud Platform, or you can run OPA as a sidecar container in your pipeline. The key is that the check happens before the apply step. If the check fails, the pipeline fails and the developer sees the violation message. This saves time because the developer fixes the issue in code rather than waiting for a manual review after deployment.

Professionals also need to understand the difference between “deny” and “audit.” A common mistake is to set a policy to “audit” and assume it blocks non-compliant resources. It does not. It only reports them. For blocking, you must use “deny.” Also, be careful with the “modify” effect: it can automatically change resources to be compliant, but it can also cause unexpected changes if not carefully designed. For example, a modify policy that adds a tag to resources might overwrite existing tags.

Finally, policy as code requires good version control. Store your policy definitions in a git repository. Use pull requests to review changes before they are deployed. This ensures that policy changes are auditable and that you can roll back if a new policy breaks something. Treat policies with the same discipline as application code, and you will avoid many operational headaches.

Policy as Code Definition and Core Mechanics

Policy as Code (PaC) is the practice of encoding infrastructure and security rules into machine-readable, version-controlled files. Instead of relying on manual approvals or unstructured documentation, teams define policies using declarative languages like Rego (Open Policy Agent), Sentinel (HashiCorp), or Azure Policy JSON. These policies are then evaluated automatically during CI/CD pipelines, runtime enforcement, or compliance scans.

The core mechanics involve three phases: definition, evaluation, and enforcement. First, an administrator writes a policy rule specifying allowed actions, resource constraints, or security baselines. For example, a policy might require that all S3 buckets have encryption enabled or that no public IP addresses are attached to VMs in production.

Second, a policy engine evaluates requests or configurations against these rules before they are applied. In AWS, this is done with Service Control Policies (SCPs) or AWS Config rules; in Azure, Azure Policy performs real-time evaluation; and for Kubernetes, OPA or Kyverno gate admission webhooks. Third, enforcement can be either deny (blocking non-compliant changes) or audit (logging violations for review).

This automation reduces human error, ensures consistency across multi-cloud environments, and provides audit trails for compliance frameworks like HIPAA, PCI-DSS, or SOC 2. For exam purposes, understanding the difference between preventive controls (deny) and detective controls (audit) is critical. Many cloud certification questions, especially in AWS SAA and Azure AZ-104, test the ability to choose the correct policy type for a given requirement.

For instance, if a company needs to block the creation of unencrypted resources, a preventive policy with a deny effect is appropriate. If the goal is to monitor existing resources for drift, an audit policy or a compliance scan is better. The CISSP exam (ISC2) frames this within the broader context of identity and access management, emphasizing that PaC aligns with the principle of least privilege and separation of duties.

PaC is becoming a standard in DevSecOps workflows, where security tests are gated before deployment. The CySA+ and Security+ exams often include scenario-based questions where you must interpret policy output or suggest a rule to remediate a vulnerability. Finally, MD-102 and MS-102 focus on Windows and Microsoft 365 policies, but the underlying concept of declarative, code-driven configuration management remains the same.

Policy as Code transforms governance from a manual, error-prone process into an automated, scalable, and auditable component of the software development lifecycle.

Policy as Code Across AWS, Azure, and Kubernetes

Different cloud providers implement Policy as Code with distinct tools and syntaxes, but the underlying principles are shared. On AWS, Policy as Code primarily manifests through IAM policies, Service Control Policies (SCPs), and AWS Config rules. IAM policies are JSON documents attached to users, groups, or roles to define what actions are allowed or denied on specific resources.

SCPs are similar but operate at the organizational unit level in AWS Organizations, allowing central governance across multiple accounts. AWS Config rules can be custom or managed, evaluating resource configurations against desired states and triggering remediation actions. The AWS SysOps Administrator and Developer Associate exams (SAA, DVA) frequently include questions about SCPs limiting account permissions or Config rules detecting non-compliant security groups.

On Azure, the primary tool is Azure Policy, which uses JSON policy definitions with effects like Deny, Audit, Append, or DeployIfNotExists. Azure Policy can be applied to management groups, subscriptions, or resource groups, and it integrates with Azure Blueprints for repeatable deployments. The AZ-104 and AZ-400 exams heavily cover Azure Policy, including how to assign initiatives, manage exemptions, and use policy remediation tasks.

For example, an exam question might ask which effect to use if you want to automatically add a tag to resources that lack it (Append) or to log violations without blocking creation (Audit). In Kubernetes, Policy as Code is enforced through admission controllers like Open Policy Agent (OPA) Gatekeeper, Kyverno, or Kubernetes native Pod Security Standards (PSS). These policies validate pod specifications, network policies, and RBAC settings before they are applied to the cluster.

The CKS (Certified Kubernetes Security Specialist) exam, while not listed, aligns with this content, but the CISSP and CySA+ exams increasingly include Kubernetes scenarios. For instance, a question might present a PodSecurityPolicy (deprecated but still tested) violation and ask for a Kyverno rule to enforce read-only root filesystems. Understanding the ecosystem is vital: OPA uses Rego, a high-level declarative language, while Kyverno uses YAML-based rules that are more approachable for Kubernetes administrators.

The SC-900 (Microsoft Security Fundamentals) introduces Azure Policy in the context of compliance and data classification, making it relevant for entry-level security roles. Across all platforms, the key concept is that policies are code, meaning they can be versioned, tested, and deployed through CI/CD pipelines. Tools like Terraform, Pulumi, and Ansible can also embed policy checks, ensuring infrastructure as code configurations are validated before deployment.

For exam success, memorize the default deny-all policy behavior, understand how policy inheritance works (explicit deny overrides allow), and practice reading small policy JSON snippets to identify what they do.

Policy as Code in CI/CD Pipelines and Release Gating

Integrating Policy as Code into CI/CD pipelines transforms security from a final audit step into a continuous, automated gate. The process begins when a developer commits infrastructure or application code to a repository. A pipeline, such as GitHub Actions, GitLab CI, Azure DevOps Pipelines, or Jenkins, triggers a series of policy checks before the code reaches production.

For infrastructure definitions (Terraform, CloudFormation, ARM templates), tools like Checkov, tfsec, or Sentinel evaluate the assets against built-in or custom policies. For example, a policy might require that all AWS S3 buckets have 'block-public-access' set to true. If the policy fails, the pipeline is aborted, and the developer receives immediate feedback, preventing non-compliant resources from being created.

This is known as 'shift-left' security, catching issues early and reducing cost and risk. In Azure DevOps, the AZ-400 exam emphasizes pipeline policies, including branch policies, required reviewers, and Azure Policy integration with Azure Pipelines. A common exam scenario: a company uses Azure Policy to enforce tagging standards, and the pipeline must verify that new resources have the required tags.

This is achieved using Azure Policy's 'AuditIfNotExists' effect, combined with a pipeline task that runs 'az policy state query' to check compliance. For application security, tools like SonarQube or Snyk can be paired with custom policies to prevent vulnerable dependencies from being deployed. The MD-102 and MS-102 exams focus on endpoint policies, but the concept extends: Intune policies are defined as JSON and deployed to devices, similar to how Azure Policy works for cloud resources.

Another critical integration is with runtime policy enforcement. For example, a Kubernetes cluster running OPA Gatekeeper continuously evaluates incoming admission requests. This means even if a pipeline bypasses checks, the cluster itself rejects non-compliant workloads.

In exam questions, you might be asked to design a solution where policies are enforced at both build time and runtime. The answer often involves a combination of pipeline gating (prevent commit) and admission control (prevent deployment). The CySA+ and Security+ exams test this through scenario-based questions where a security analyst must identify when a policy violation was introduced-at code commit, during build, or at runtime.

Understanding the difference between 'shift-left' (pre-commit/pre-build) and 'drift detection' (runtime) is essential. Compliance frameworks like SOC 2 require evidence that policies are enforced, and CI/CD logs provide an immutable audit trail. For the CISSP, this maps to the software development security domain, specifically the need for security controls in the deployment phase.

Policy as Code in pipelines ensures that every deployment is validated against the same set of rules, reducing the attack surface and maintaining compliance posture over time.

Policy as Code Exam Tips and Common Pitfalls

Many exam questions about Policy as Code test the ability to interpret policy outputs or choose the correct enforcement mechanism. A common pitfall is confusing 'Deny' with 'Audit' effects. In Azure Policy, 'Deny' prevents resource creation or update if the condition is met, while 'Audit' allows the operation but logs a violation.

Similarly, in AWS SCPs, an explicit deny always overrides any allow, and the effect 'Deny' is used to block actions at the organizational level. Another frequent mistake is misunderstanding policy inheritance. For example, if a subscription in Azure has an 'Allow' policy but the management group has a 'Deny' policy, the deny takes precedence.

In AWS Organizations, if an SCP denies an action at the root level, it cannot be overridden by any child account. The CISSP exam frames this under the concept of 'policy as a control' and tests the principle of least privilege through SCP scenarios. For instance, a question might describe a junior admin who accidentally gave full admin access via an IAM policy, and you need to choose an SCP that blocks all actions except specific ones.

Another common exam topic is 'policy drift'-when actual resource configurations differ from the intended policy. Tools like AWS Config or Azure Policy's 'Remediation' tasks can automatically revert non-compliant resources. The CySA+ exam often includes a scenario where a security analyst finds a resource out of compliance, and you must select the best remediation method (manual vs.

automated). For the MD-102 and MS-102 exams, a common pitfall is assuming that Intune policies apply instantly to all devices; in reality, policy refresh intervals and device check-ins affect timing. Exam questions may ask you to troubleshoot why a policy hasn't been applied, and the answer often involves checking certificate trust or network connectivity.

Another pitfall is ignoring the evaluation order of policies in Kubernetes admission controllers. Mutating webhooks run before validating webhooks, so a mutating policy that adds labels must be applied before a validating policy that checks for labels. The Security+ and CySA+ exams test this through process-flow questions.

Many students struggle with Rego syntax for OPA. While you don't need to be an expert, you should be able to read a simple Rego rule and identify that it denies public S3 buckets or enforces encryption. For example, a rule like 'deny[msg] { input.

request.operation = "CREATE"; bucket := input.request.object.spec; not bucket.spec.publicAccess; msg := "S3 bucket must block public access"}' is common. Practice interpreting these in context.

Finally, a critical tip for all exams: always look for the 'effect' or 'action' field in policy definitions, as questions often ask what the policy will do (deny, audit, allow). By mastering these nuances, you can quickly eliminate incorrect options and choose the best answer.

Troubleshooting Clues

Azure Policy assignment not evaluating resources

Symptom: Newly created resources show 'Not started' or 'Unknown' compliance state; policy evaluation does not trigger automatically.

Azure Policy evaluation is triggered by resource creation, update, or a scheduled scan. If the policy is assigned at a scope that does not include the resource group, or if there is a service principal permission issue (e.g., missing Reader role), evaluation fails. Also, custom policies with incorrect conditions may not match any resources.

Exam clue: In AZ-104, a question may describe a policy that worked on test resources but fails on production. The key is to check the scope and RBAC permissions of the policy assignment's managed identity.

AWS SCP blocking legitimate actions across accounts

Symptom: Users in a child account receive 'AccessDenied' errors on actions that should be allowed by IAM policies within that account.

SCPs act as a guardrail at the organization level. Even if an IAM policy grants an action, if an SCP at the root, OU, or account level denies it (explicit deny), the action is blocked. Also, SCPs cannot grant permissions; they only filter them. The issue often arises when a deny rule is too broad or when policy size limits (5,120 characters) are exceeded.

Exam clue: CISSP and SAA exams test this: an SCP that denies 'ec2:*' will block all EC2 actions, regardless of IAM policies. Students must look for the 'Effect: Deny' field in the SCP JSON.

Kubernetes OPA Gatekeeper constraint not enforcing

Symptom: Pods with violations are still created; the constraint appears in the cluster but does not block admission.

Common reasons include: the constraint template is not installed correctly, the enforcement action is set to 'dryrun' instead of 'deny', or the webhook configuration is missing (e.g., no ValidatingWebhookConfiguration). Also, the constraint may only apply to namespaces with a specific label, and the pod's namespace lacks it.

Exam clue: CySA+ and security exams may ask why a Gatekeeper policy did not prevent a deployment. The answer often involves checking the 'enforcementAction' field in the constraint YAML.

Terraform Sentinel policy failing but resources still created

Symptom: The 'terraform plan' shows a policy violation, but 'terraform apply' still creates the resource.

Sentinel policies are only enforced if the policy is set to 'hard-mandatory' or 'soft-mandatory' level. If it is set to 'advisory' or the policy file is not correctly loaded during apply, the violation is logged but not blocked. Another cause: the policy may only be evaluated during plan, not apply, in some configurations.

Exam clue: AZ-400 and Terraform certification exams test the difference between 'hard-mandatory' (deny) and 'advisory' (warn). Students must know that only hard-mandatory policies actually block the apply.

Azure Policy 'DeployIfNotExists' remediation task not running

Symptom: Non-compliant resources are not automatically fixed; remediation task shows 'Failed' or 'Skipped'.

The managed identity of the policy assignment must have sufficient permissions (e.g., Contributor role) on the target resources to deploy the remediation. Also, if there is a conflict (e.g., the resource already has a configuration that cannot be overwritten), the task fails. Finally, policy definitions with 'DeployIfNotExists' require a template that may have incorrect parameter values.

Exam clue: In AZ-104, a question might ask why a remediation fails. Common answer: the identity lacks RBAC permissions. Always verify the identity's role assignments.

AWS Config rule showing 'INSUFFICIENT_DATA' indefinitely

Symptom: The rule never evaluates resources, showing no compliance results.

This occurs when the AWS Config rule's trigger configuration (e.g., 'ConfigurationChanges' or 'Scheduled') is misconfigured, or the IAM role for AWS Config does not have permissions to describe resources. Also, if the resource type is not supported by AWS Config, evaluations will not occur.

Exam clue: SAA and SysOps exams: 'INSUFFICIENT_DATA' is a clue that the rule cannot evaluate. Students must check the rule's trigger and the Config service role's trust policy.

Kyverno policy applying to unintended namespaces

Symptom: A Kyverno policy designed for production namespaces also blocks operations in development namespaces.

The policy's 'spec.rules.match' or 'spec.rules.exclude' fields may not include namespace selectors. By default, Kyverno policies apply to all resources if no namespace exclusion is set. Also, using broad resource descriptions (like '*') without namespace restrictions can cause overreach.

Exam clue: Security exams test policy scoping: you must add an 'exclude' block for certain namespaces or use 'match' with specific labels to limit enforcement.

Git-based policy checks failing in CI/CD pipeline

Symptom: The pipeline run fails due to policy violation, but the same commit passed locally with no issues.

Local environment may use different tool versions or skip policy files. Also, the CI pipeline may have environment variables that are missing or different (e.g., cloud credentials). Another common cause: the pipeline uses a different branch where the policy file is not merged yet.

Exam clue: AZ-400 and GitHub Actions exams: this scenario tests the concept of 'policy as code in CI'. The best fix is to ensure the pipeline pulls the correct branch and runs the same policy checks as local pre-commit hooks.

Memory Tip

Remember 'PaC' like 'Pack' your rules into code, so they travel with your infrastructure and enforce themselves everywhere.

Learn This Topic Fully

This glossary page explains what Policy as code means. For a complete lesson with labs and practice, see the topic guide.

Covered in These Exams

Current Exam Context

Current exam versions that test this topic — use these objectives when studying.

Related Glossary Terms

Quick Knowledge Check

1.A security team wants to ensure that all IAM user creation requests in AWS are automatically denied unless the user's email domain ends with '@company.com'. Which type of policy should they implement?

2.In Azure, you assign a policy with effect 'Deny' at the subscription scope. A resource group within that subscription also has a policy assignment with effect 'Audit' for the same rule. What is the actual effect on newly created resources?

3.A Kubernetes administrator applies a Gatekeeper constraint that denies pods with 'privileged: true'. However, a new pod with privileged: true is still created. Which is the most likely cause?

4.An organization uses Terraform Sentinel to enforce that all EC2 instances must have tags 'Environment' and 'Owner'. A developer runs 'terraform apply' and the instance is created without tags. What went wrong?

5.A company uses Azure Policy with a 'DeployIfNotExists' effect to automatically enable encryption on new storage accounts. You notice that many storage accounts remain unencrypted even after creation. What is the most likely cause?

Frequently Asked Questions

Do I need to be a programmer to use policy as code?

You need some familiarity with code, but the languages used (like JSON or Rego) are relatively simple. Many tools also offer graphical policy builders. Start with basic conditions and work up.

Can policy as code be used for on-premises environments?

Yes, tools like OPA can be used to enforce policies on any system that can make API calls, including on-premises servers and applications. However, it is most commonly used with cloud infrastructure.

Is policy as code only for security?

No, it is also used for cost management (enforcing instance sizes), operational compliance (tagging policies), and data governance (data retention rules).

What is the difference between Azure Policy and AWS Config?

Both are native policy as code services. Azure Policy is deeply integrated into Azure Resource Manager and can deny or modify resources. AWS Config is primarily an auditing and evaluation service; to block resources, you typically combine it with AWS Lambda or Service Control Policies.

How do I test policy as code before deploying it?

Most tools provide a test or simulation mode. For Azure Policy, you can use the ‘what if’ feature. For OPA, you can run the policy against a test input using the CLI. Always test in a non-production environment first.

Can policy as code slow down deployments?

It adds a few seconds to the pipeline to evaluate policies. This is usually negligible compared to the time saved by avoiding manual reviews and fixing issues in production.

What happens if two policies conflict?

In Azure, the most restrictive policy at the most specific scope wins. In OPA, you must explicitly define conflict resolution logic. Always design policies to be consistent and avoid contradictions.

Is policy as code the same as 'guardrails'?

Yes, the term 'guardrails' is often used to describe the automated enforcement that policy as code provides. It sets boundaries that prevent teams from going outside the allowed configuration.

Summary

Policy as code transforms security and compliance rules from static documents into executable, automated enforcement mechanisms. It is a fundamental shift from manual, reactive compliance to proactive, automated governance. By writing policies in code and integrating them into CI/CD pipelines and infrastructure provisioning, organizations can catch violations before they reach production, enforce rules consistently across thousands of resources, and provide clear audit trails for regulators.

For IT certification learners, understanding policy as code is crucial because it appears in many exams, from AWS and Azure to CompTIA and CISSP. You need to know the tools available in each cloud platform, the difference between policy enforcement and access control, and how to interpret policy definitions. The most common exam pitfalls involve confusing policy effects (audit vs. deny), misapplying scope, and mixing up RBAC with policy as code.

The takeaway is that policy as code is a core skill for modern cloud administrators, DevOps engineers, and security professionals. It enables faster, safer deployments and is a key component of any mature cloud governance strategy. Start by learning the policy tools in your preferred cloud platform, practice writing and testing policies, and always think of policy enforcement as an automated gate rather than a manual check.