Validate Yaml Files with Dry-Run Command in Kubernetes

Itacen Sabacok | Jan 4, 2023

When you change something in specs of yaml file, it would be good if run dry-run first before applying it because its safer.

You can use the --dry-run=client flag to preview the object that would be sent to your cluster, without really submitting it.

here are some examples;

 1# find only file names of local changes using git command
 2changedFilesArr=($(git diff --name-only))
 3repoDir=/work/business/repos/super-app
 4
 5for i in "${changedFilesArr[@]}"
 6do
 7	echo "file path -> "$i
 8	kubectl apply -f $repoDir/$i --dry-run=client
 9	echo ""
10done
 1# find last commit id
 2lastCommitId=($(git log --format="%H" -n 1))
 3# get file names in last commit(with above commit id)
 4changedFilesArr=($(git show --pretty="" --name-only $lastCommitId))
 5repoDir=/work/business/repos/super-app
 6
 7for i in "${changedFilesArr[@]}"
 8do
 9	echo "file path -> "$i
10	kubectl apply -f $repoDir/$i --dry-run=client
11	echo ""
12done
 1# find all yaml files in directory and run dry-run for all
 2# you can add "-not -path ..." command to exclude folders
 3changedFilesArr=($( find . -name *.yaml -not -path "./tf/*" -not -path "./ans/*" ))
 4repoDir=/work/business/repos/super-app
 5
 6for i in "${changedFilesArr[@]}"
 7do
 8	echo "file path -> "$i
 9	kubectl apply -f $repoDir/$i --dry-run=client
10	echo ""
11done