Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Composer Install From Private Repository In a Privately Hosted GitLab Server Using GitLab Tokens

The problem.

You need to be able to composer install private PHP packages that are hosted on your personal GitLab server, and you need to do this through the use of GitLab tokens, probably because you are setting up a CI/CD pipeline.

Steps

Generate personal token:

First you need to generate your Gitlab token. If this is for one package/repository, you can do generate this froThe token must have api or read_api scope (go with read_api). Read repository on its own won't work.

composer config gitlab-token.gitlab.mydomain.com $GITLAB_PACKAGES_TOKEN
    "repositories": [
        {
            "type": "git",
            "url": "https://gitlab.mydomain.com/diverse-interactive/laravel-package-user-auth.git"
        },

When using repository tokens, or using a personal-access-token, the configuration is the same. Reading some online posts led me to believe one needed to specify a username, but this is not the case.

{
    "gitlab-token": {
        "gitlab.mydomain.com" : "Md8JSXXXXXXXXXXXWaWX"
    }
}

... down in the config of the composer.json file you need to add your gitlab domain. E.g.:

    "config": {
        "gitlab-domains" : ["gitlab.mydomain.com"],

If you don't specify this, then it defaults to gitlab.com

Now add the lines to your Dockerfile for running the composer install. Alternatively, you may be using the composer install from inside the .gitlab-ci.yml file.

RUN cd /var/www/my-site && composer config gitlab-token.gitlab.mydomain.com $GITLAB_PACKAGES_TOKEN
RUN cd /var/www/my-site && composer install && rm auth.json

Update your docker-compose file to specify the variable. Doing it like this allows it to not be hardcoded into the docker-compose file, so your secret wont be in version control. Instead it will be loading the variable from your env vars

services:
  app:
    build:
      context: .
      dockerfile: ./docker/Dockerfile
      args:
        - GITLAB_PACKAGES_TOKEN
    env_file:
      - ./.env

If you are using docker build command rather than docker-compose, then you need to add the build argument like so:

docker build --build-arg GITLAB_PACKAGES_TOKEN=$GITLAB_PACKAGES_TOKEN ...

Asking For User / Password

Unfortunately, switching away from SSH key-based system results it in asking me for username/password even though I have the auth.json file. It turns out one just has to keep hitting enter.

References

Last updated: 21st September 2021
First published: 16th June 2021