apiVersion: policy.jspolicy.com/v1beta1
kind: JsPolicy
metadata:
name: "create.resource.example"
spec:
operations: ["CREATE"]
resources: ["pods"]
javascript: |
// create() is able to create any resource in the kubernetes cluster
// create() takes parameters in the form of (object)
// this will create a new configmap in the namespace with the same name as
// the pod and contains all the container names.
const result = create({
kind: "ConfigMap",
apiVersion: "v1",
metadata: {
"name": request.object.metadata.name,
"namespace": request.object.metadata.namespace
},
data: {
containers: (request.object.spec?.containers || []).map(container => container.name).join(",")
}
});
if (!result.ok) {
// check for a specific error type
if (result.reason === "AlreadyExists") {
warn(`ConfigMap already exists`);
} else {
warn(`Error creating ConfigMap (Reason ${result.reason}): ${result.message}`);
}
} else {
print("Created ConfigMap", result.object);
}