Creating a policy
As an example, you create a simple validation policy that processes Pod creation requests.
The policy looks at the metadata.name
attribute of the Pod and rejects pods having an invalid name.
It’s list of invalid names should be configurable by end users of the policy.
The policy settings look something like:
invalid_names:
- bad_name1
- bad_name2
The policy should accept the creation of a Pod like the following one:
apiVersion: v1
kind: Pod
metadata:
name: nginx
spec:
containers:
- name: nginx
image: nginx:latest
It should reject the creation of a Pod like:
apiVersion: v1
kind: Pod
metadata:
name: bad_name1
spec:
containers:
- name: nginx
image: nginx:latest
Scaffolding the new policy project
You can create a new policy project by using cargo generate
with the
template project.
First, install cargo-generate
. This requires openssl-devel.
cargo install cargo-generate
Now scaffold the project as follows:
cargo generate --git https://github.com/kubewarden/rust-policy-template \
--branch main \
--name demo
The command produces output like:
🔧 Creating project called `demo`...
✨ Done! New project created /<some-path-name>/demo
This creates the new policy project in the demo
sub-directory.
If you plan to make use of the GitHub container registry functionality in the demo, you need to enable improved container support. |
Testing
You can try:
cargo test
This tests the generated scaffolding. If everything is correctly in place you’ll see a series of compilation messages ending with output like:
running 4 tests
test settings::tests::validate_settings ... ok
test tests::accept_request_with_non_pod_resource ... ok
test tests::accept_pod_with_valid_name ... ok
test tests::reject_pod_with_invalid_name ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s