1

I'm trying manage our k8s cluster from gitlab repository (where all manifests are stored). When gitlab receives commit, sends webhook to jenkins server and this pipeline is triggered:

pipeline {
    agent any

    stages {
        stage('Apply Kubernetes files') {
            steps {
              withKubeConfig([credentialsId: 'kubeconfig']) {
              sh 'git diff --name-only ${gitlabBefore} ${gitlabAfter} | grep -E "^k8s.*ya?ml" | xargs -n1 -r kubectl apply -f'
               }
            }
        }
     }   
}

Applying changes works properly, but there is a problem when commit contains deleting files. I wanted to use command kubectl delete -f but file which I want to delete doesn't exist in repository.

Is there any way to delete kubernetes objects when repository doesn't have a manifest file?

I was trying revert previous commit in jenkins containter, then kubectl delete -f but it doesn't work.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
truegunner
  • 21
  • 3

1 Answers1

0

You can get contents of any file from any commit using git show command.

So something like

kubectl delete -f <(git show HEAD~:your_file.yaml)

should work. Here HEAD~ refers to previous commit.

git diff can also filter output based on different conditions, so you can actually get all deleted manifests and work with them. So in your case something like this should work:

git diff --diff-filter='D' --name-only ${gitlabBefore} ${gitlabAfter} | \
grep -E "^k8s.*ya?ml" | xargs -i kubectl delete -f <(git show ${gitlabBefore}:{})
Andrew
  • 3,912
  • 17
  • 28