# Policy as Code

Policy as Code expresses governance and security requirements as version-controlled, machine-evaluable rules that automated workflows can test and enforce.

Cloud concept. Updated 2026-10-29. Page: https://blowstack.com/tools/cloud-concepts-hub/policy-as-code

> Policy as Code turns written requirements into executable checks against infrastructure definitions, deployment plans, requests, or running resources. It helps teams apply consistent controls across accounts and environments, detect violations early, and retain reviewable evidence of policy changes and evaluation results.

Practice exams covering Policy as Code: [ANS-C01 AWS Certified Advanced Networking - Specialty](https://blowstack.com/practice-exams/aws-certified-advanced-networking-specialty), [DOP-C02 AWS Certified DevOps Engineer - Professional](https://blowstack.com/practice-exams/aws-certified-devops-engineer-professional), [AIP-C01 AWS Certified Generative AI Developer - Professional](https://blowstack.com/practice-exams/aws-certified-generative-ai-developer-professional), [SCS-C03 AWS Certified Security - Specialty](https://blowstack.com/practice-exams/aws-certified-security-specialty), [SAP-C03 AWS Certified Solutions Architect - Professional](https://blowstack.com/practice-exams/aws-certified-solutions-architect-professional).

## 6 key aspects of Policy as Code

Policy as Code combines executable rules, software delivery practices, explicit enforcement, and ongoing evaluation to apply governance consistently.

1. **Executable requirements**: Translate requirements into deterministic rules with clear inputs and actionable outcomes. Define how missing properties, unknown values, and evaluation errors affect the result.
2. **Versioning and testing**: Review policy changes through version control and test them with compliant and noncompliant examples. Record policy versions alongside evaluation results so teams can explain why a deployment passed or failed.
3. **Explicit enforcement points**: Run checks in pull requests, deployment pipelines, provisioning controls, or runtime evaluations as appropriate. A policy becomes preventive only when a violation blocks the relevant operation and bypass paths are controlled.
4. **Consistent multi-account deployment**: Apply shared policy rules to approved infrastructure templates before distributing them across accounts and Regions. Separate deployment orchestration from policy evaluation, and restrict who can change either.
5. **Layered validation**: Combine template linting, security policy evaluation, permission boundaries, and runtime compliance checks. Each addresses different failure modes; syntactically valid infrastructure is not necessarily secure infrastructure.
6. **Managed exceptions and rollout**: Use scoped, time-limited exceptions with accountable owners rather than disabling checks broadly. Stage policy changes and monitor their impact before enforcing them across all workloads.

## Cloud services for Policy as Code

CodePipeline can orchestrate a workflow in which CodeBuild lints infrastructure definitions, tests policy rules, and evaluates the proposed deployment. Only artifacts that pass required checks proceed to CloudFormation, with StackSets distributing approved baselines across accounts and Regions. AWS Organizations adds permission guardrails that can restrict prohibited actions outside the pipeline. AWS Config evaluates supported running-resource configurations to identify noncompliance introduced after deployment. Together, these services separate validation, deployment, permission control, and runtime assessment rather than treating any single check as complete enforcement.

- **[AWS CloudFormation](https://blowstack.com/tools/cloud-services-hub/aws-cloudformation)**: CloudFormation provides declarative infrastructure deployment, while StackSets distribute baseline templates across accounts and Regions. CloudFormation Guard is a separate policy-evaluation tool, and cfn-lint is a template-validation tool that can run before deployment; CloudFormation Hooks can provide provisioning-time validation.
- **[AWS Config](https://blowstack.com/tools/cloud-services-hub/aws-config)**: AWS Config evaluates recorded resource configurations against rules, including custom policy rules authored with Guard. Conformance packs package rules and remediation actions for repeatable deployment, complementing predeployment checks with evaluation of running resources.
- **[AWS Organizations](https://blowstack.com/tools/cloud-services-hub/aws-organizations)**: AWS Organizations supports centrally managed service control policies that limit available permissions in member accounts. Managing these policies as reviewed, versioned artifacts applies Policy as Code to organization-level permission guardrails; service control policies do not grant permissions or validate every resource property.
- **[AWS CodeBuild](https://blowstack.com/tools/cloud-services-hub/aws-codebuild)**: CodeBuild can execute cfn-lint, CloudFormation Guard, policy unit tests, and third-party policy engines as automated build steps. Configure failed policy evaluations to fail the build and preserve reports for troubleshooting and audit evidence.
- **[AWS CodePipeline](https://blowstack.com/tools/cloud-services-hub/aws-codepipeline)**: CodePipeline can place validation and policy-test stages before infrastructure deployment. Protect pipeline configuration and deployment roles so that required checks cannot be bypassed by an alternative deployment path.

## Policy as Code exam questions

Real practice exam questions on Policy as Code, with the correct answer and its explanation.

### Question 1 (SAP-C03)

**Question:**

A company manages 90 workload accounts with AWS Organizations. An SCP attached to the workload OU requires CostCenter and Project tags on selected resource creation APIs. The company has verified that these APIs support tagging on creation and the required condition keys. The SCP currently works as intended.

The governance team frequently changes the tagging requirements. A recent SCP update passed JSON validation but unexpectedly denied correctly tagged deployments. The team rolled back the update manually.

The company now requires every tagging-policy change to have peer-reviewed version history, automated regression evidence that verifies authorization behavior before production deployment, and a traceable link between the tested policy and the deployed policy. Tests must verify that otherwise-authorized, correctly tagged requests succeed and that requests missing either required tag fail.

Which release process meets these requirements?

**Correct answer:** Store the SCP and request-test fixtures in version control. Apply each candidate to an isolated test OU that mirrors the relevant production policy hierarchy. Using an otherwise-authorized member-account test role, execute requests with valid tags, each required tag omitted separately, and both tags omitted. Require expected outcomes and peer approval before deploying the identical policy artifact to production, and retain results linked to its version.

**Explanation:** This process treats the governance policy and its expected behavior as testable software artifacts. Actual API tests in a representative authorization context detect unintended denials and enforcement gaps. Review gates, promotion of the identical tested artifact, and version-linked results provide change control and auditable evidence.

### Question 2 (AIP-C01)

**Question:**

A company operates Amazon Bedrock assistants in several AWS accounts. Each release includes a manifest containing the target account, AWS Region, guardrail identifier, and guardrail version. The application already applies the specified guardrail to every interaction. Only a central release pipeline can modify production application configurations.

Responsible AI policy requires each release to use an approved, numbered guardrail version whose configuration includes the required denied topics and sensitive-information actions. Teams can reference existing guardrails instead of creating them in their deployment templates. Auditors require reproducible evidence of which policy requirements were evaluated for each release. A release must not proceed if compliance cannot be established.

Which implementation best meets these requirements?

**Correct answer:** Add a mandatory pipeline step that invokes an AWS Lambda function to evaluate the resolved release manifest against version-controlled, tested policy rules. Retrieve the exact referenced guardrail version in the target account and Region, verify its approval and required controls, and block deployment on violations or verification errors. Retain the manifest, policy revision, evaluated configuration, and results.

**Explanation:** This turns responsible AI requirements into executable release controls. Resolving the reference and inspecting the exact numbered version covers guardrails that are not defined in the deployment template. Failing closed prevents releases when verification is incomplete, and the retained artifacts make each decision reproducible and auditable.

### Question 3 (SCS-C03)

**Question:**

A company deploys an application into development and production AWS accounts by using a pipeline that generates AWS CloudFormation templates from shared, version-controlled infrastructure definitions. Environment configuration files specify different instance sizes and database capacities. The generator resolves these settings into explicit resource property values in each output template.

A production configuration change recently caused the generator to disable database storage encryption, even though the shared definitions had passed security review. The security team requires every environment-specific template to satisfy executable security rules before provisioning. The team must also be able to prove that each deployed template is exactly the artifact that passed validation.

Which pipeline design meets these requirements?

**Correct answer:** Generate each environment's template and run cfn-lint and CloudFormation Guard with the approved security rules against that output. Block deployment on any required check failure, and deploy the exact validated artifact from immutable storage using its recorded version and checksum.

**Explanation:** The generated templates contain the actual environment-specific resource properties, so validating those outputs catches unsafe configuration overrides. Mandatory linting and policy checks prevent failed artifacts from progressing. Deploying the same immutable, versioned artifact and retaining its checksum and validation results establishes a traceable link between validation and deployment.

### Question 4 (DOP-C02)

**Question:**

A company distributes reusable network patterns through a centrally maintained AWS CloudFormation macro. Application templates invoke the macro, which generates security groups and ingress rules based on application parameters. Application teams can also declare security group resources directly.

A deployment pipeline currently evaluates the submitted templates against version-controlled security rules. An audit finds that a template passed these checks even though the macro generated an ingress rule allowing TCP port 22 from 0.0.0.0/0.

The company must automatically reject deployments containing prohibited ingress rules before provisioning any resources, whether the rules are declared directly or generated by the macro. The relevant properties in the transformed templates use literal values. Only the pipeline can deploy stacks, and the company wants to retain the macro-based patterns.

Which pipeline change meets these requirements?

**Correct answer:** Create a CloudFormation change set and wait for its creation to complete. Retrieve its template with GetTemplate and TemplateStage set to Processed. Evaluate that template with CloudFormation Guard rules covering security groups and ingress resources. Execute that same change set only if the evaluation succeeds.

**Explanation:** The processed template includes resources produced by the macro as well as resources declared directly. Creating a change set processes transforms without provisioning stack resources. Evaluating the processed template with explicit Guard rules and blocking execution on failure enforces the standard before provisioning. Executing the same change set preserves the connection between the evaluated definitions and the deployment.

### Question 5 (ANS-C01)

**Question:**

A company deploys VPC security groups through AWS CloudFormation in multiple accounts and Regions. Administrators can also modify security groups directly for emergency maintenance. A network security standard prohibits unrestricted IPv4 or IPv6 ingress to specified administrative ports, including ingress rules whose port ranges contain those ports. The list of administrative ports changes periodically.

The security team must review and regression-test changes to the standard's automated checks, reject noncompliant templates before deployment, and continuously audit deployed security groups for violations introduced through any deployment path. Audit evidence must identify the approved check version and its evaluation results. Automatic remediation is not required.

Which implementation meets these requirements?

**Correct answer:** Version and review CloudFormation Guard rules and AWS Config custom-rule code that implement the standard. Test both implementations against compliant and noncompliant fixtures. Make Guard failures block deployment, deploy the Config rules in every target account and Region with continuous security group recording, and centrally retain compliance results and release records that identify the deployed check versions.

**Explanation:** This implements the standard as reviewable, testable executable checks at both required stages. Guard blocks violating templates before provisioning, while AWS Config evaluates running security groups, including direct changes. Regression fixtures should cover IPv4, IPv6, broad port ranges, and all-protocol rules. Versioned releases and retained evaluation records provide traceable audit evidence without requiring remediation.

## Practice Policy as Code in a full exam

Questions on Policy as Code in each practice exam, with every answer option and an explanation for each:

- [DOP-C02](https://blowstack.com/practice-exams/aws-certified-devops-engineer-professional): 8 questions
- [AIP-C01](https://blowstack.com/practice-exams/aws-certified-generative-ai-developer-professional): 6 questions
- [SCS-C03](https://blowstack.com/practice-exams/aws-certified-security-specialty): 4 questions
- [SAP-C03](https://blowstack.com/practice-exams/aws-certified-solutions-architect-professional): 1 question
- [ANS-C01](https://blowstack.com/practice-exams/aws-certified-advanced-networking-specialty): 1 question

## What is Policy as Code

Policy as Code treats governance requirements as software artifacts rather than relying only on documents and manual reviews. Engineers express requirements in a rule language or general-purpose code, store them in version control, test their behavior, and run them through automated evaluation. Examples include requiring encryption for storage, prohibiting unrestricted administrative network access, and requiring ownership tags. Policies should produce actionable results that identify the resource, violated requirement, and expected correction.

Infrastructure as code and Policy as Code serve different purposes. Infrastructure as code describes resources to create or modify; Policy as Code evaluates whether those definitions or their resulting resources satisfy requirements. A reusable infrastructure template can contain secure defaults, but those defaults are not an enforcement boundary if callers can override them or deploy through another path. A practical design combines approved templates with independent policy checks and appropriately restricted deployment permissions.

In a deployment pipeline, validate the infrastructure definition before provisioning. For AWS CloudFormation, cfn-lint checks templates against resource specifications and other validation rules, helping detect invalid properties and configuration mistakes. AWS CloudFormation Guard evaluates structured data against explicitly authored policy rules, such as requiring an encryption property or restricting allowed resource configurations. Passing cfn-lint does not establish compliance with an organization's security requirements, and Guard does not enforce rules merely because a rule file exists. The pipeline must execute the checks and stop deployment when required checks fail.

For example, a pull request that introduces an unencrypted database should fail a policy test before deployment. The same repository can include passing and failing fixtures to verify that the rule detects missing encryption settings without rejecting approved configurations. Third-party infrastructure tools can use comparable workflows, such as evaluating Terraform plan JSON with Open Policy Agent. Evaluate the artifact that will actually be deployed, and account for unresolved values: static checks cannot always determine properties that become known only during deployment.

Across accounts and Regions, CloudFormation StackSets can distribute approved baseline templates and updates consistently. StackSets provide deployment orchestration, not a general-purpose security policy evaluator. Validate templates before distributing them, control deployment roles, and use staged rollouts to limit the impact of mistakes. Where appropriate, CloudFormation Hooks can add provisioning-time checks, while organization-level permission controls can restrict prohibited actions through other deployment paths.

Predeployment checks do not replace assessment of running resources. Console changes, alternative automation, and changing dependencies can introduce noncompliance after a successful deployment. Runtime evaluations, such as AWS Config rules, complement pipeline checks; detection and remediation are separate capabilities and must be configured deliberately. Drift detection identifies differences from declared infrastructure but does not independently prove security compliance.

The main trade-offs are policy maintenance, incomplete evaluation context, false positives, and the disruption caused by incorrect blocking rules. Begin new rules in reporting mode when appropriate, test them against representative workloads, and promote them to enforcement after review. Exceptions should have an owner, justification, scope, and expiration. Protect policy repositories and pipeline configuration as carefully as deployment credentials, because an actor who can weaken checks or bypass the pipeline can undermine the control.

## Learn Policy as Code in lessons

5 short lessons on Policy as Code in 4 certification courses.

- SAP-C03: Policy as Code: enforceable cost-allocation tagging rules (Premium), https://app.blowstack.com/lessons/policy-as-code-enforceable-cost-allocation-tagging-rules-sap-c03
- AIP-C01: Policy as Code: organization-wide AI policy enforcement (Premium), https://app.blowstack.com/lessons/policy-as-code-organization-wide-ai-policy-enforcement-aip-c01
- SCS-C03: Policy as Code: enforcing deployment policy gates (Premium), https://app.blowstack.com/lessons/policy-as-code-enforcing-deployment-policy-gates-scs-c03
- DOP-C02: Policy as Code: enforcing requirements on reusable IaC (Premium), https://app.blowstack.com/lessons/policy-as-code-enforcing-requirements-on-reusable-iac-dop-c02
- SCS-C03: Policy as Code vs. Infrastructure as Code (Premium), https://app.blowstack.com/lessons/policy-as-code-vs-infrastructure-as-code-scs-c03
