DEV Community

klo2k
klo2k

Posted on • Edited on

Get Git to remember passwords - git credential manager examples

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
Enter fullscreen mode Exit fullscreen mode

Add password, clone from repo

Add password

git credential approve <<'EOT'
url=https://example.com/jsmith/testrepo.git
username=jsmith
password=abc123
EOT
Enter fullscreen mode Exit fullscreen mode

Clone repo - no password asked / exposed 😉️

git clone https://jsmith@example.com/jsmith/testrepo.git
Enter fullscreen mode Exit fullscreen mode

Clean-up

rm ~/.git-credentials
exit
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)