Skip to main content
Version: Next 🚧

Creating a new validation policy

This tutorial covers creating a policy that validates the hostnames of Pod objects.

The policy is to reject all Pods that use one or more hostnames on the deny list. You provide policy configuration using runtime settings.

To summarize, the policy settings should look like this:

denied_hostnames:
- bad-host
- forbidden-host

The policy rejects the creation of this Pod:

apiVersion: v1
kind: Pod
metadata:
name: nginx
spec:
hostname: bad-host
containers:
- name: nginx
image: nginx:latest

However, it accepts the creation of this Pod:

apiVersion: v1
kind: Pod
metadata:
name: nginx
spec:
hostname: allowed-host
containers:
- name: nginx
image: nginx:latest

Scaffolding a new policy project​

You can create a new policy project using the template repository. Select the "Use this template" green button near the top of the page and follow GitHub's wizard.

Clone the repository locally and update the package.json file to reflect your policy details:

{
"name": "your-policy-name",
"version": "1.0.0",
"description": "Your policy description",
"repository": {
"type": "git",
"url": "https://github.com/your-username/your-policy-name"
}
}

Make sure to use a repository path that matches your actual GitHub repository.

Testing​

Provided the necessary tools are in place, the make all command builds the annotated-policy.wasm target. The command make e2e runs tests using bats with kwctl.

Output from the make commands
$ make all

npm install

added 393 packages, and audited 394 packages in 9s

59 packages are looking for funding
run `npm fund` for details

found 0 vulnerabilities
npm run build

> kubewarden-js-policy-template@0.1.1 build
> npx webpack --config webpack.config.cjs

asset bundled.js 5.49 KiB [emitted] [minimized] (name: main)
asset types.d.ts 430 bytes [emitted]
asset index.d.ts 11 bytes [emitted]
./src/index.ts 3.65 KiB [built] [code generated]
./node_modules/@kubewarden/policy-sdk/dist/bundle.js 3.83 KiB [built] [code generated]
webpack 5.106.2 compiled successfully in 817 ms
npm install

up to date, audited 394 packages in 638ms

59 packages are looking for funding
run `npm fund` for details

found 0 vulnerabilities
javy build dist/bundled.js -C plugin=node_modules/@kubewarden/policy-sdk/plugin/javy-plugin-kubewarden.wasm -o policy.wasm
kwctl annotate policy.wasm --metadata-path metadata.yml --output-path annotated-policy.wasm
$ make e2e

bats e2e.bats
e2e.bats
✓ reject because hostname is on deny list
✓ accept because hostname is not on the deny list
✓ accept because the deny list is empty
✓ accept because pod has no hostname set
✓ accept non-pod resources

5 tests, 0 failures