Using custom git credentials in Gitlab CI
Please note that this is only applicable when using the HTTPS git protocol
Recently I was trying to automate releasing an npm package from my Gitlab CI
pipeline. The plugin I was using
(release-it) can bump the version
number in package.json for me, create a versioned git tag and push these
changes to the repository.
However, I ran into permission issues – caused by our Gitlab company setup –
where they did not allow me to use the default Gitlab CI token. Instead I needed
to use custom git credentials using a token with more privileges, in order to be
allowed to push to the protected master branch.
Specifying custom credentials
The credentials to be used can be put in a .git-credentials file in the home
folder (as per the
git docs)
in the following format:
You then have to configure git to use the store credential helper by running:
The problem
Although I had created the ~/.git-credentials file before attempting to push,
for some reason my custom credentials weren't being picked up by git. Instead,
the default gitlab-ci-token user combined with the default $CI_JOB_TOKEN
password were still being used.
The solution
After some more debugging, it turned out that the git remote was being set including the default credentials:
In order for git to use my custom credentials specified in ~/.git-credentials,
I had to remove the default remote and replace it with the git url without
any credentials specified. For this I used the predefined
$CI_PROJECT_URL
variable from Gitlab CI, like so:
This resulted in the expected output:
Without the credentials being hardcoded into the git remote url, my credentials
in ~/.git-credentials are now being picked up as expected!