I'm trying to create a bash script that initializes a server and clones a git repository as part of initialization.
The installing user will set a personal access token (PAT) as an environment variable $TOKEN to clone via script. I want each subsequent user that pulls or pushes code to this cloned repository to set their PAT via environment variable $TOKEN, instead of using the original PAT the installer used.
However, when the script clones the repository gitconfig stores the interpreted value of the $TOKEN instead of variable $TOKEN so any subsequent pull/push uses the original installer's PAT.
i.e. when I do:
git clone https://oauth2:[email protected]/repo.git
gitconfig says:
[remote "origin"]
url = https://oauth2:[email protected]/repo.git
fetch = +refs/heads/*:refs/remotes/origin/*
when I want it to say:
[remote "origin"]
url = https://oauth2:[email protected]/repo.git
fetch = +refs/heads/*:refs/remotes/origin/*
I can't figure out how to force each user to use their token each time in a simple way.
Any ideas? Thanks
You should avoid placing the token into the URL at all, since this is exposed to other users and saved in the configuration file. Instead, you can have the user configure a special credential helper to read from the environment, as outlined in the Git FAQ (substituting author below):
$ git config credential.helper \
'!f() { echo username=author; echo "password=$TOKEN"; };f'
If you want to do this as part of a clone operation, you can do that with the -c argument to clone:
$ git clone -c credential.helper= \
-c credential.helper='!f() { echo username=author; echo "password=$TOKEN"; };f' \
https://gitlab.com/repo.git
The additional empty value for credential.helper causes any existing credential helpers to be removed, preventing the addition of this token into the user's credential helper. If you'd like the user to be able to save it, then remove that directive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With