Policy as code expresses security and compliance rules as executable or declarative checks against infrastructure configuration or state. These checks detect noncompliant metadata before changes reach production, reducing reliance on manual review and shortening the long-term path to deployment. section 8.3
A practical policy-as-code workflow includes:
- Extract metadata from infrastructure configuration or system state, often as JSON. section 8.3.1
- Parse relevant fields and compare actual values with expected security or compliance values. section 8.3.1
- Fail the test when a rule is violated, then correct the configuration before production deployment. section 8.3.2 section 8.4
- Classify checks as hard mandatory, soft mandatory, or advisory so enforcement matches the risk. section 8.4
Blocking an open database firewall
A database firewall should use restrictive, least-privilege access rather than the GCP range 0.0.0.0/0. A Python test loads the generated JSON configuration, retrieves the firewall rule’s source_ranges, and fails when that permissive range appears. Equivalent checks can target Azure network security groups or AWS security groups through their corresponding fields. section 8.3.2
Policy engines support platform security tests, industry or regulatory standards, and custom policies. No single tool covers every use case, so teams may combine tools or extend existing ones. Detailed test names and error messages explain both the violation and its correction; modular tests and shared repositories let multiple teams reuse and update common policies. section 8.3.1 section 8.3.4
Listing 8.3 Using a test to parse the firewall rule for 0.0.0.0
import json
import pytest
from main import APP_NAME, CONFIGURATION_FILE
@pytest.fixture(scope="module")
def resources():
with open(CONFIGURATION_FILE, 'r') as f: #1
config = json.load(f) #1
return config['resource'] #2
@pytest.fixture
def database_firewall_rule(resources): #3
return resources[0][ #3
'google_compute_firewall'][0][APP_NAME][0] #3
def test_database_firewall_rule_should_not_allow_everything( #4
database_firewall_rule):
assert '0.0.0.0/0' not in \ #5
database_firewall_rule['source_ranges'], \ #5
'database firewall rule must not ' + \ #6
'allow traffic from 0.0.0.0/0, specify source_ranges ' + \ #6
'with exact IP address ranges' #6
Inspect the Python test that loads infrastructure JSON, locates the database firewall rule, and rejects an unrestricted source range. section 8.3.2


