Delete a file from GitLab repository using gitlab-ci.yml

How can I delete a file from my GitLab repository using gitlab-ci.yml
?
I already used a sh command in my gitlab-ci.yml
file but it didn't work.
Here's the command I tried: sh 'rm -rf [myfile]'
.
Does anyone have another idea or another suggestion?
Answer
When you run a script command in a gitlab runner it is only working on the local files. i.e. rm -rf [myfile]
is only going to delete the local file.
If you want the runner to delete the file from the repository, you will have to script commands to update the repo like any other git user. Perhaps something like this:
delete-and-push:
stage: cleanup
image: alpine:latest
before_script:
- apk add git openssh
- git config --global user.email "Read more"
- git config --global user.name "GitLab CI"
script:
- git checkout $CI_COMMIT_BRANCH
- git rm path/to/your/file.txt
- git commit -m "Delete file.txt from pipeline"
- git push https://oauth2:${CI_PUSH_TOKEN}@gitlab.com/${CI_PROJECT_PATH}.git HEAD:$CI_COMMIT_BRANCH
This is making use of a CI_PUSH_TOKEN
from a CI/CD variable to authenticate. The value would be a Personal Access Token or a Project Access Token with write_repository
scope.
Enjoyed this article?
Check out more content on our blog or follow us on social media.
Browse more articles