Force git to use HTTPS


snippets git

Recently I encountered an issue where a CI tool could not fetch certain dependencies as the SSH key used for cloning the main project did not have access to the other repositories.

To work around this, I opted to clone the private dependencies via https, passing the credentials in the URI.

The magic to force this without changing composer.json:

# Set the COMPOSER_USER and COMPOSER_TOKEN environment variables to a user which has access to clone these repos.
git config --global url."https://${COMPOSER_USER}:${COMPOSER_TOKEN}@gitlab.example.com/".insteadOf "git@gitlab.example.com:"

You can also clone public repos via the https endpoint rather than ssh like this:

git config --global url."https://github.com/".insteadOf 'git@github.com:'

In context of a GitLab CI .gitlab-ci.yml file, it looks like this:

build:
  script:
    # Use https clone URLs.
    - git config --global url."https://${COMPOSER_USER}:${COMPOSER_TOKEN}@gitlab.example.com/".insteadOf "git@gitlab.example.com:"
    - git config --global url."https://github.com/".insteadOf 'git@github.com:'
    - composer --no-progress install

Of course this can also be reversed, if you have a https clone URL, you can change it to a ssh or git uri.

Interestingly CircleCI uses this method to force cloning github repos via ssh - https://discuss.circleci.com/t/github-forced-through-ssh-protocol/5332/2