Kubernetes Mutating Admission Policies with Kyverno
Let's take our Kubernetes security journey to the next level! In our previous blog, we explored the power of Kyverno for validating admission policies. If you missed it, catch up here:
Now, we're excited to dive into the world of Mutating Admission Policies with Kyverno. In this blog, we'll uncover the potential of Kyverno by implementing few fascinating Mutating policies that will streamline your cluster management and enhance security.
Assuming you've installed Kyverno on your cluster (if not, run bellow command to install it)
kubectl create -f https://github.com/kyverno/kyverno/releases/download/v1.12.0/install.yaml
let's dive into implementing Mutating Admission Policies.
Our first scenario: adding default security context to pods.
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: add-default-securitycontext
spec:
rules:
- name: add-default-securitycontext
match:
any:
- resources:
kinds:
- Pod
mutate:
patchStrategicMerge:
spec:
securityContext:
+(runAsNonRoot): true
+(runAsUser): 1000
+(runAsGroup): 3000
+(fsGroup): 2000
Now, Apply above policy.

Now try to create a pod without security context

If you exec into the pod, you'll see that the sleep command runs as a non-root user (1000)!"

Our second scenario: adding default resource requests (e.g., CPU and memory) for containers in pods that don't specify them
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: add-default-resources
spec:
rules:
- name: add-default-requests
match:
any:
- resources:
kinds:
- Pod
mutate:
patchStrategicMerge:
spec:
containers:
- name: "*"
resources:
requests:
+(cpu): 50m
+(memory): 64Mi


Now when you describe created pod, You will see,

These can you production usecase.
Our Third scenario is add default label in particular pod. For instance, if you want there should be label "backup-needed=yes" in every database related pod.
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: database-backup-labeling
spec:
rules:
- name: assign-backup-database
match:
any:
- resources:
kinds:
- Pod
selector:
matchLabels:
type: database
mutate:
patchStrategicMerge:
metadata:
labels:
+(backup-needed): "yes"

Now , if you check labels

That's a wrap for today's blog! Thanks for joining me on this Kubernetes journey. Stay tuned for our next blog, where we'll dive into more exciting topics related to Kubernetes. Until then, keep on hustling and remember to always keep your cluster secure and your containers shipping!



