Back to Policies

Restrict Scale

Pod controllers such as Deployments which implement replicas and permit the scale action use a `/scale` subresource to control this behavior. In addition to checks for creations of such controllers that their replica is in a certain shape, the scale operation and subresource needs to be accounted for as well. This policy, operable beginning in Kyverno 1.9, is a collection of rules which can be used to limit the replica count both upon creation of a Deployment and when a scale operation is performed.

View on GitHub

Policy Definition

apiVersion: kyverno.io/v2beta1
kind: ClusterPolicy
metadata:
name: restrict-scale
annotations:
policies.kyverno.io/title: Restrict Scale
policies.kyverno.io/category: Other
policies.kyverno.io/severity: medium
kyverno.io/kyverno-version: 1.9.0
policies.kyverno.io/minversion: 1.9.0
kyverno.io/kubernetes-version: "1.24"
policies.kyverno.io/subject: Deployment
policies.kyverno.io/description: Pod controllers such as Deployments which implement replicas and permit the scale action use a `/scale` subresource to control this behavior. In addition to checks for creations of such controllers that their replica is in a certain shape, the scale operation and subresource needs to be accounted for as well. This policy, operable beginning in Kyverno 1.9, is a collection of rules which can be used to limit the replica count both upon creation of a Deployment and when a scale operation is performed.
spec:
validationFailureAction: Audit
background: false
rules:
- name: scale-max-eight
match:
any:
- resources:
kinds:
- Deployment/scale
validate:
message: The replica count for this Deployment may not exceed 8.
pattern:
(status):
(selector): "*type=monitoring*"
spec:
replicas: <9
- name: scale-max-eight-annotations
match:
any:
- resources:
kinds:
- Deployment/scale
context:
- name: parentdeploy
apiCall:
urlPath: /apis/apps/v1/namespaces/{{request.namespace}}/deployments?fieldSelector=metadata.name={{request.name}}
jmesPath: items[0]
- name: dept
variable:
jmesPath: parentdeploy.metadata.annotations."corp.org/dept"
default: empty
validate:
message: The replica count for this Deployment may not exceed 8.
deny:
conditions:
all:
- key: "{{dept}}"
operator: Equals
value: engineering
- key: "{{request.object.spec.replicas}}"
operator: GreaterThan
value: 8
- name: create-max-four
match:
any:
- resources:
kinds:
- Deployment
selector:
matchLabels:
type: monitoring
validate:
message: The replica count for this Deployment may not exceed 4.
pattern:
spec:
replicas: <5

Related Policies