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.
Related Posts
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/my-group-name/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
- stephenlewis.me - How to use a private GitLab repository as a Composer dependency
- getcomposer.org Docs - Gitlab Token
- Private Composer Repositories with GitLab
- Stack Overflow - How to fetch gitlab repo using composer and cache
- Stack Overflow - Pass a variable to a Dockerfile from a docker-compose.yml file
First published: 16th June 2021