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:
https://${GITLAB_USER_LOGIN}:${GITLAB_API_TOKEN}@git.company.url
You then have to configure git to use the store
credential helper by running:
$ git config credential.helper store
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:
$ git remote -v
origin https://gitlab-ci-token:[MASKED]@git.company.url/my-project.git (fetch)
origin https://gitlab-ci-token:[MASKED]@git.company.url/my-project.git (push)
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:
$ git remote remove origin
$ git remote add origin "${CI_PROJECT_URL}.git"
This resulted in the expected output:
$ git remote -v
origin https://git.company.url/my-project.git (fetch)
origin https://git.company.url/my-project.git (push)
Without the credentials being hardcoded into the git remote url, my credentials
in ~/.git-credentials
are now being picked up as expected!