Last active
April 23, 2025 15:02
-
-
Save angeloxx/a0d7fdb413f6b3c145f61b0a9c53fe8d to your computer and use it in GitHub Desktop.
Kyverno rule to adapt container's requested memory to a fraction of the limit for guaranteed workloads
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
apiVersion: kyverno.io/v1 | |
kind: ClusterPolicy | |
metadata: | |
name: mutate-container-requests-based-on-limits | |
annotations: | |
pod-policies.kyverno.io/autogen-controllers: none | |
policies.kyverno.io/title: Adjust Container Memory Requests Based on Limits | |
policies.kyverno.io/category: Other | |
policies.kyverno.io/subject: Workload | |
policies.kyverno.io/minversion: 1.11.0 | |
kyverno.io/kubernetes-version: "1.23" | |
policies.kyverno.io/description: | | |
Automatically sets memory requests to 90% of limits for Pod containers when initial | |
requests and limits are equal. Parent object will not be affected | |
policies.kyverno.io/usage: | | |
- Apply to clusters to enforce memory request/limit ratio | |
spec: | |
rules: | |
- name: mutate-container-requests-based-on-limits | |
match: | |
any: | |
- resources: | |
kinds: | |
- Pod | |
preconditions: | |
all: | |
- key: "{{ request.operation }}" | |
operator: In | |
value: | |
- CREATE | |
context: | |
- name: ratio | |
variable: | |
value: "0.9" | |
mutate: | |
foreach: | |
- list: request.object.spec.containers | |
preconditions: | |
any: | |
- key: "{{ element.resources.requests.memory || '-1' }}" | |
operator: Equals | |
value: "{{ element.resources.limits.memory || '+1' }}" | |
patchesJson6902: |- | |
- path: "/spec/containers/{{`{{ elementIndex }}`}}/resources/requests/memory" | |
op: add | |
value: | |
"{{ multiply(`{{ regex_replace_all('([0-9]*)(.*)', '{{ element.resources.limits.memory }}', '${1}') }}`,`{{ ratio }}`) }}{{ regex_replace_all('([0-9]*)(.*)', '{{ element.resources.limits.memory }}', '${2}') }}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment