Back to Policies

Add PSA Labels

Pod Security Admission (PSA) can be controlled via the assignment of labels at the Namespace level which define the Pod Security Standard (PSS) profile in use and the action to take. If not using a cluster-wide configuration via an AdmissionConfiguration file, Namespaces must be explicitly labeled. This policy assigns the labels `pod-security.kubernetes.io/enforce=baseline` and `pod-security.kubernetes.io/warn=restricted` to all new Namespaces if those labels are not included.

View on GitHub

Policy Definition

apiVersion: policies.kyverno.io/v1alpha1
kind: MutatingPolicy
metadata:
name: add-psa-labels
annotations:
policies.kyverno.io/title: Add PSA Labels
policies.kyverno.io/category: Pod Security Admission, EKS Best Practices
policies.kyverno.io/severity: medium
kyverno.io/kyverno-version: 1.7.1
policies.kyverno.io/minversion: 1.6.0
kyverno.io/kubernetes-version: "1.24"
policies.kyverno.io/subject: Namespace
policies.kyverno.io/description: Pod Security Admission (PSA) can be controlled via the assignment of labels at the Namespace level which define the Pod Security Standard (PSS) profile in use and the action to take. If not using a cluster-wide configuration via an AdmissionConfiguration file, Namespaces must be explicitly labeled. This policy assigns the labels `pod-security.kubernetes.io/enforce=baseline` and `pod-security.kubernetes.io/warn=restricted` to all new Namespaces if those labels are not included.
spec:
matchConstraints:
resourceRules:
- apiGroups:
- ""
apiVersions:
- v1
operations:
- CREATE
- UPDATE
resources:
- namespaces
matchConditions:
- name: needs-psa-labels
expression: |
!has(object.metadata.labels) ||
!object.metadata.labels.exists(k, k == 'pod-security.kubernetes.io/enforce') ||
!object.metadata.labels.exists(k, k == 'pod-security.kubernetes.io/warn')
variables:
- name: enforceValue
expression: |
has(object.metadata.labels) &&
object.metadata.labels.exists(k, k == 'pod-security.kubernetes.io/enforce') ?
object.metadata.labels['pod-security.kubernetes.io/enforce'] : 'baseline'
- name: warnValue
expression: |
has(object.metadata.labels) &&
object.metadata.labels.exists(k, k == 'pod-security.kubernetes.io/warn') ?
object.metadata.labels['pod-security.kubernetes.io/warn'] : 'restricted'
mutations:
- patchType: ApplyConfiguration
applyConfiguration:
expression: |
Object{
metadata: Object.metadata{
labels: {
"pod-security.kubernetes.io/enforce": string(variables.enforceValue),
"pod-security.kubernetes.io/warn": string(variables.warnValue)
}
}
}

Related Policies