CodeWitchBella
← Back to blog index

Use GitHub token to clone private repositories via HTTPS

Published: 2023-10-01

If you ever find yourself wanting to clone a private github repository via HTTPS by using GitHub token, you landed in the right place. But first, ask yourself if this is truly something you want and consider alternative solutions as this probably will only work on your machine and in CI, not on other devs machines (speaking from experience here). But if you still want to do this (I ended up choosing an alternative solution), here's how.

Without furhter ado, here is the code

# create file which specifies the token
echo "https://git:${{ secrets.GITHUB_TOKEN }}@github.com" > ${RUNNER_TEMP}/git-credentials.store
# set git to look for the file
git config --global credential.helper 'store --file ${RUNNER_TEMP}/git-credentials.store'
# do whatever needs to clone private repositories via https, in my case it was yarn install
yarn --immutable
# delete the file
rm -f ${RUNNER_TEMP}/git-credentials.store

Since you are probably doing this in CI, please also make sure that you clean the store once you're done — even if the next step fails. Here's how to do that in github actions

- name: Install
  shell: bash
  run: |
    set -xe
    mkdir -p ${{ runner.temp }}
    git config --global credential.helper 'store --file ${{ runner.temp }}/git-credentials.store'
    echo "https://git:${{ inputs.token }}@github.com" > ${{ runner.temp }}/git-credentials.store
    # Use your newly gained access here
- name: Cleanup
  shell: bash
  if: always()
  run: rm -f ${{ runner.temp }}/git-credentials.store

The way this works is we set git-credential-store as git credential helper. It's a program which provides git with credentials for accessing resources, which is exactly what we want here. It allows you to specify file for loading the data.

Lastly, if you want to used this in Dockerfile, use --mount=type=secret to give docker access to your file without saving it to the build history.