Skip to content

Instantly share code, notes, and snippets.

@chipzoller
Created May 31, 2023 00:27
Show Gist options
  • Save chipzoller/59b853addb966ec206e0e5c4d40efe99 to your computer and use it in GitHub Desktop.
Save chipzoller/59b853addb966ec206e0e5c4d40efe99 to your computer and use it in GitHub Desktop.
Kyverno policy for OpenCost
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
creationTimestamp: "2023-03-07T00:24:33Z"
generation: 1
name: check-namespace-costs-cm
resourceVersion: "1741990"
uid: bdbbf92e-6948-4553-a5af-c74f97436b77
annotations:
policies.kyverno.io/title: Namespace Cost Exceeded
policies.kyverno.io/minversion: 1.10.0
policies.kyverno.io/category: Cost Management
policies.kyverno.io/severity: medium
policies.kyverno.io/subject: Namespace
policies.kyverno.io/description: >-
This policy checks for namespace costs and generates a violation if the cost exceeds the allocated cost specified in the namespace-quota-cm config map.
spec:
background: true
rules:
- context:
- apiCall:
method: GET
service:
url: http://opencost.opencost:9090/model/allocation/compute?window=1d&aggregate=namespace&step=1d&accumulate=false
name: result
- name: totalCost
variable:
value: '{{ result.data[0].["{{ request.object.metadata.name }}"][0].totalCost
|| ''0'' }}'
- name: costConfigMap
configMap:
name: namespace-quota-cm
namespace: nirmata
- name: allocatedCost
variable:
value: '{{ costConfigMap.data."{{ request.object.metadata.name }}" || ''0'' }}'
match:
any:
- resources:
kinds:
- Namespace
name: check-namespace-cost
validate:
deny:
conditions:
all:
- key: '{{ allocatedCost }}'
operator: GreaterThan
value: '0'
- key: '{{ totalCost }}'
operator: GreaterThan
value: '{{ allocatedCost }}'
message: namespace {{request.object.metadata.name}} cost {{ totalCost }} exceeds
maximum cost threshold {{ allocatedCost }}
validationFailureAction: Audit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment