Skip to main content

list() Function

The list() function is able to retrieve a list of objects from the kubernetes cluster either cached or directly. list() takes parameters in the form of list(Kind, apiVersion, ListOptions?). If an error occurred a Javascript exception will be raised, otherwise an array of objects will be returned.

If you call get() or list() within a policy, jsPolicy will by default try to get the resources from its internal cache to save time and ease pressure on the api server. You do not need to configure in jsPolicy which resources are cached by jsPolicy as it will figure this out automatically by tracking which resources are called in get() and list(). If resources are not needed anymore in the cache (after no get() or list() has been called for a specific time), jsPolicy will delete its internal cache for that resource automatically.

You can explicitly tell jsPolicy to make a direct call to the api server instead of retrieving the resources from the cache via the get or list options.


kind: JsPolicy
name: "list.resource.example"
operations: ["CREATE"]
resources: ["pods"]
javascript: |
// list() can list any resource in the kubernetes cluster either from cache or directly
// list() takes parameters in the form (Kind, apiVersion, ListOptions?) and returns an array
// ListOptions can be 'namespace', 'labelSelector' and 'cache'
// If no ListOptions are specified all resources from the cluster are listed
const pods = list("Pod", "v1", {
namespace: request.namespace
if (pods.length >= 10) {
deny("No more pods allowed in namespace " + request.namespace);
// list all pods in cluster with label selector from cache
const myLabelPods = list("Pod", "v1", {
labelSelector: "my-label=my-value"
if (myLabelPods.length > 0) {
print("Found pod with my-label=my-value");
// deny if there is an ubuntu pod in the namespace
pods.forEach(pod => === "ubuntu" && deny("there is an ubuntu pod in the namespace"));