Sometimes it's necessary to use password-based authentication via https
when using remote repo.
When used in CI/CD pipelines, we need to do this non-interactively, and not expose password in the remote's URL.
To do this, we can use git's own credential manager.
Here are some examples to help us understand and use it.
TL;DR (Full Example)
Setup
# Get a shell into git container
docker run --rm -it --entrypoint=/bin/sh alpine/git:v2.34.2
# Store credentials to file
git config --global credential.helper store
# Note: To store in memory (for 1 day)
# git config --global credential.helper 'cache --timeout=86400'
# Clean out existing credentials
rm ~/.git-credentials
# Force non-interactive mode
export GIT_TERMINAL_PROMPT=0
Add password, clone from repo
Add password
git credential approve <<'EOT'
url=https://example.com/jsmith/testrepo.git
username=jsmith
password=abc123
EOT
Clone repo - no password asked / exposed 😉️
git clone https://jsmith@example.com/jsmith/testrepo.git
Clean-up
rm ~/.git-credentials
exit
More Examples
Save credentials
git credential approve <<'EOT'
url=https://example.com
username=user0
password=0000
EOT
git credential approve <<'EOT'
url=https://example.com/test-group/test-repo1.git
username=user1
password=1111
EOT
git credential approve <<'EOT'
url=https://example.com/test-group/test-repo2.git
username=user2
password=2222
EOT
Get credentials
git credential fill <<'EOT'
url=https://example.com/test-group/test-repo1.git
username=user1
EOT
git credential fill <<'EOT'
url=https://example.com/test-group/test-repo2.git
username=user2
EOT
git credential fill <<'EOT'
url=https://example.com
username=user0
EOT
Selectively remove credentials
git credential reject <<'EOT'
url=https://example.com
username=user2
EOT
# Ensure it's removed - expect to error-out with "fatal: could not read Password for 'https://user2@example.com': terminal prompts disabled"
git credential fill <<'EOT'
url=https://example.com/test-group/test-repo2.git
username=user2
EOT
Top comments (0)