gitlab ci php composer

Running Composer and npm scripts with deployment via SCP in GitLab CI/CD

This guide covers the building of dependencies of a PHP project while compiling assets via an npm script using GitLab CI/CD.

While it is possible to create your own image with custom PHP and Node.js versions, for brevity we use an existing Docker image that contains both PHP and Node.js installed.

The next step is to install zip/unzip packages and make composer available. We place these in the before_script section:

This makes sure we have all requirements ready. Next, run composer install to fetch all PHP dependencies and npm install to load Node.js packages. Then run the npm script. We need to append them into before_script section:

All these operations put all files into a build folder, which is ready to be deployed to a live server.

How to transfer files to a live server

You have multiple options: rsync, SCP, SFTP, and so on. For now, use SCP.

To make this work, you must add a GitLab CI/CD Variable (accessible on gitlab.example/your-project-name/variables ). Name this variable STAGING_PRIVATE_KEY and set it to the private SSH key of your server.

Security tip

Create a user that has access only to the folder that needs to be updated.

After you create that variable, make sure that key is added to the Docker container on run:

And this is basically all you need in the before_script section.

How to deploy

As we stated above, we need to deploy the build folder from the Docker image to our server. To do so, we create a new job:

What’s the deal with the artifacts? We tell GitLab CI/CD to keep the build directory (later on, you can download that as needed).

Why we do it this way

If you’re using this only for stage server, you could do this in two steps:

The problem is that there’s a small period of time when you don’t have the app on your server.

Therefore, for a production environment we use additional steps to ensure that at any given time, a functional app is in place.

Where to go next

Источник

Testing PHP projects

This guide covers basic building instructions for PHP projects.

Two testing scenarios are covered: using the Docker executor and using the Shell executor.

Test PHP projects using the Docker executor

While it is possible to test PHP apps on any system, this would require manual configuration from the developer. To overcome this we use the official PHP Docker image that can be found in Docker Hub.

This allows us to test PHP projects against different versions of PHP. However, not everything is plug ‘n’ play, you still need to configure some things manually.

Let’s first specify the PHP image that is used for the job process. (You can read more about what an image means in the runner’s lingo reading about Using Docker images.)

The official images are great, but they lack a few useful tools for testing. We need to first prepare the build environment. A way to overcome this is to create a script which installs all prerequisites prior the actual testing is done.

Let’s create a ci/docker_install.sh file in the root directory of our repository with the following content:

You might wonder what docker-php-ext-install is. In short, it is a script provided by the official PHP Docker image that you can use to easily install extensions. For more information read the documentation.

Last step, run the actual tests using phpunit :

Finally, commit your files and push them to GitLab to see your build succeeding (or failing).

Test against different PHP versions in Docker builds

Testing against multiple versions of PHP is super easy. Just add another job with a different Docker image version and the runner does the rest:

Custom PHP configuration in Docker builds

Of course, my_php.ini must be present in the root directory of your repository.

Test PHP projects using the Shell executor

The shell executor runs your job in a terminal session on your server. To test your projects, you must first ensure that all dependencies are installed.

For example, in a VM running Debian 8, first update the cache, and then install phpunit and php5-mysql :

Finally, push to GitLab and let the tests begin!

Test against different PHP versions in Shell builds

The phpenv project allows you to easily manage different versions of PHP each with its own configuration. This is especially useful when testing PHP projects with the Shell executor.

You have to install it on your build machine under the gitlab-runner user following the upstream installation guide.

Using phpenv also allows to easily configure the PHP environment with:

Important note: It seems phpenv/phpenv is abandoned. There is a fork at madumlao/phpenv that tries to bring the project back to life. CHH/phpenv also seems like a good alternative. Picking any of the mentioned tools works with the basic phpenv commands. Guiding you to choose the right phpenv is out of the scope of this tutorial.

Install custom extensions

Since this is a pretty bare installation of the PHP environment, you may need some extensions that are not currently present on the build machine.

To install additional extensions simply execute:

Extend your tests

Using atoum

Instead of PHPUnit, you can use any other tool to run unit tests. For example you can use atoum :

Using Composer

Access private packages or dependencies

If your test suite needs to access a private repository, you need to configure the SSH keys to be able to clone it.

Use databases or other services

This functionality is covered in the CI services documentation.

Testing things locally

With GitLab Runner 1.0 you can also test any changes locally. From your terminal execute:

Example project

We have set up an Example PHP Project for your convenience that runs on GitLab.com using our publicly available shared runners.

Want to hack on it? Simply fork it, commit, and push your changes. Within a few moments the changes are picked by a public runner and the job begins.

Источник

GitLab-CI PHPunit Composer laravel

I am new to GitLab-CI and Docker, I am stuck getting a runner to run my phpunit builds. Following the instructions here: https://gitlab.com/gitlab-org/gitlab-ci-multi-runner/blob/master/docs/install/linux-repository.md

However, The container per their instructions obviously doesn’t contain the tools I need. So question is, what is the configuration when registering a multi-runner to have a runner that supports phpunit, composer so I can test my laravel builds.

2 Answers 2

Obviously this config is for my application running on Yii2. So you need to adjust it per your requirements.

Inline with what Arman P. said. When running your tests, make sure you have a docker image which contains all the tools that you will need for your build/test.

You have two options:

You can build your own image, with all the tools you need, and maintain this as your project evolves; or,

you can simply install a basic image from the docker hub and install all the tools before you run your jobs.

Both options have their pros and cons:

Option (1) gives you complete control, but you would need to add this to a private registry which the CI can pull from (Gitlab gives you a private registry support). The only slight con here is that you would have to setup the private registry (e.g Gitlab’s) first. Not too difficult, and only need to do it once.

But then it is up to you to maintain the images, etc.

Option (2) allows you to run all the tools without having to maintain a private registry or the docker containers. You simply run the install scrips before your jobs as Arman P. mentioned. The disadvantage on that is that your jobs and builds/tests take longer to run as you now have to wait for the install to happen before every run.

A simple example: Using option (2)

We need PHPUnit and composer.

So, use a container from the public docker hub which has php: select one that has the version of PHP you want to test (e.g. 5.6 or 7). Let’s assume 5.6.

In that container we need to install composer and PHPUnit before we can run our tests. This is what your CI file might look like:

Quick summary of what this actually does

The first job that runs will be the «build app» as it occurs in the first stage, build. Before the script runs in this job, the global before_script runs, which installs git and composer (Composer requires Git). Then the script runs and installs all our composer dependencies. Done.

Note here, that due to the stage setup, the output of the build stages are automatically made available in the test stage. So we don’t have to do anything, Gitlab will pass all the files for us!

Источник

Almat.su (Almat.pro)

Блог Алмата Жандаулетова

gitlab ci php composer. Смотреть фото gitlab ci php composer. Смотреть картинку gitlab ci php composer. Картинка про gitlab ci php composer. Фото gitlab ci php composer

gitlab ci php composer. Смотреть фото gitlab ci php composer. Смотреть картинку gitlab ci php composer. Картинка про gitlab ci php composer. Фото gitlab ci php composer

Gitlab CI/CD на примере PHP проекта

В этой статье мы воспользуемся замечательным инструментом Gitlab CI/CD для автоматизации непрерывной интеграции. На примере PHP проекта, который включает в себя этапы: composer install, то есть установка всех зависимостей и библиотек; этап тестирования, запуск юнит тестов; и наконец деплой на сервер, в качестве которого будет выступать облачный PAAS Heroku; познакомимся с понятиями конвейера или pipeline, конфигурацией через gitlab-ci.yml, артефактами, разделением всего этого на stages и запуском jobs. Поехали…

Что такое Gitlab?

Gitlab это такой Github на стероидах, по крайнем мере был им. Сейчас после покупки Github-a Microsoft, после колоссальных вложений, на Github-е начали появляться новые фишки: Github Actions, проверка кода и, после многолетнего ожидания, впервые появились бесплатные приватные репозитории 😮. Молодец Microsoft. А ведь старички знают, все эти штуки изначально были в Gitlab. СI/CD и пайплайн одним из первых появился на Gitlab. Помню, когда пайплайн только только начал внедряться в Bitbucket, на Gitlab он уже существовал давно. Еще Bitbucket для бесплатного пользования pipeline предлагал 500 минут в месяц, в то время как Gitlab, уже на тот момент, предлагал 2000 минут для бесплатного аккаунта!

Конечно не забываем о такой киллер фиче, как установка Gitlab на собственном сервере. Интересно, когда такое Github внедрить…

Что такое CI/CD Pipeline?
PHP «MVP»

Что из себя должен представлять минимальный PHP проект. Естественно он должен собираться через composer, иметь отделенный от корня проекта entrypoint(public/index.php), запускаться на PHP > 7, и конечно же иметь автотесты. Много автотестов, которые запускаются автоматически 🙂

Также он должен быстро доставляться до клиента, то есть на прод.

Gitlab CI/CD дает нам такие прекрасные возможности и нужно ими воспользоваться. У нас будут три шага, от начала написания кода, до доставки всего этого на сервер.

Build — наш проект будет автоматически собираться из репозитория, устанавливаться все зависимости и пакеты, чтобы он был готов к запуску.

Tests — проверка кода, запуск тестирования, поиск потенциальных багов, проверка на прочность.

Deploy — деплой на сервер, внесение изменении в видимый продукт.

Как начать?

В конечном итоге, наш файл будет выглядеть так:

Источник

Непрерывная интеграция/внедрение приложения Symfony с помощью docker-compose и GitLab CI

В статье я поделюсь своим опытом автоматизации всего процесса разработки приложения Symfony с нуля от настройки инфраструктуры до деплоя в production. От development- и до production-окружения для запуска приложения будет использоваться docker-compose, а все процедуры непрерывной интеграции/внедрения будут запускаться через GitLab CI/CD Pipelines в docker-контейнерах.

Подразумевается, что вы знакомы с docker и docker-compose. Если нет или вы не знаете как его установить, я подготовил инструкцию по подготовке локального окружения разработчика. Фактически, для работы над приложением потребуется только Docker, VirtualBox и, опционально, Yarn.

Запуск приложения локально

Я подготовил скелет приложения и выложил его на GitHub. Всё написанное ниже относится к приложениям, созданным на основе этого шаблона и к инфраструктуре, необходимой для запуска такого приложения.

Чтобы запустить приложение локально, нужно выполнить следущие команды:

composer в контейнере php настроен таким образом, что папка vendor находится внутри контейнера, а не на хосте, и не оказывает влияние на быстродействие в локальном окружении разработчика.

Подготовка и настройка инфраструктуры

В боевых условиях для работы системы потребуется три сервера: GitLab — сервер для управления репозиториями Git и Container Registry, Docker для production — сервер для production-сайтов и Docker для разработки — сервер для pre-production и тестовых сайтов разработчиков.

Настройка сервера с GitLab и Container Registry

С инструкциями по установке GitLab и Container Registry можно ознакомиться на сайте gitlab.com.

По умолчанию для GitLab Container Registry требуется настройка SSL сертификатов. Мы будем использовать один и тот же сертификат и для Container Registry, и для Web-интерфейса GitLab. Создать SSL-сертификат можно с помощью сервиса LetsEncrypt.

После изменения в файле gitlab.rb нужно перегрузить GitLab через gitlab-ctl restart и настроить crontab для обновления сертификатов:

Настройка сервера с Docker для production

С инструкцией по установке Docker можно ознакомиться на сайте docs.docker.com.

Дополнительно нужно создать локальную сеть для назначения контейнерам внутренних IP адресов:

Кроме Docker на сервер нужно установить nginx и certbot-auto от LetsEncrypt.

Nginx будет проксировать запросы к веб-серверам в контейнерах Docker. С инструкцией по установке Nginx можно ознакомиться на сайте nginx.org.

Обновление будущих SSL-сертификатов должно быть настроено сразу же так, как с на сервере с GitLab:

Настройка сервера с Docker для разработки

С инструкцией по установке GitLab CI Runner можно ознакомиться на сайте docs.gitlab.com.

Запуск GitLab Runner:

Над проектом будут работать несколько разработчиков, им нужно выдать доступ так, чтобы они ничего не сломали и не мешали друг другу.

Создание Master-пользователя

На сервере Docker для production нужно создать пользователя master и добавить в группу docker :

Далее нужно зайти под новым пользователем и создать id_rsa ключ без passphrase:

Этот ключ будет использоваться для SSH-доступа на сервер и для доступа в git-репозитории разработчиков.

Создание пользователя-разработчика

На сервере Docker для разработки нужно создать пользователя dev1 (имя может быть любым):

Далее нужно зайти под новым пользователем и создать id_rsa ключ без passphrase:

Этот ключ будет использоваться для SSH-доступа на сервер, он не должен быть известен кому-либо из разработчиков.

Основной репозиторий проекта можно поместить в произвольную группу.

ПеременнаяЗначение
COMPOSER_GITHUB_TOKENСоздать токен на странице https://github.com/settings/tokens
SSH_PRIVATE_KEYзаполнить её содержимым файла id_rsa пользователя master
NETWORK_NAME_MASTERgraynetwork
SERVER_NAME_MASTERsite-staging.ru
NETWORK_IP_MASTERвыбрать свободный IP в подсети graynetwork
NETWORK_NAME_PRODUCTIONgraynetwork
SERVER_NAME_PRODUCTIONsite-production.ru
NETWORK_IP_PRODUCTIONвыбрать свободный IP в подсети graynetwork
DEPLOY_USER_MASTERmaster
DEPLOY_HOST_MASTERdocker-server-prod.ru
DEPLOY_DIRECTORY_MASTER/home/master/site-staging.ru
DEPLOY_USER_PRODUCTIONmaster
DEPLOY_HOST_PRODUCTIONdocker-server-prod.ru
DEPLOY_DIRECTORY_PRODUCTION/home/master/site-production.ru
PROJECT_FORKS

ПеременнаяЗначение
COMPOSER_GITHUB_TOKENСоздать токен на странице https://github.com/settings/tokens
SSH_PRIVATE_KEYзаполнить её содержимым файла id_rsa пользователя dev1
NETWORK_NAME_MASTERgraynetwork
SERVER_NAME_MASTERsite-dev1.ru
NETWORK_IP_MASTERвыбрать свободный IP в подсети graynetwork
DEPLOY_USER_MASTERdev
DEPLOY_HOST_MASTERdocker-server-dev.ru
DEPLOY_DIRECTORY_MASTER/home/dev1/site-dev1.ru
PROJECT_FORKS

В конце нужно донастроить основной репозиторий. Нужно добавить строку с адресом репозитория разработчика в переменную PROJECT_FORKS для синхронизации ветки stable в новом репозитории. И выдать роль Reporter пользователю dev1 в основном репозитории.

Последний шаг до начала работы – настройка Nginx на серверах с Docker. Этот Nginx будет настраиваться вручную, и все HTTP/HTTPS-запросы к приложениям Symfony будут им проксироваться в выбранный IP-адрес во внутренней, ранее созданной, подсети Docker (см. переменные NETWORK_NAME_. и NETWORK_IP_. ).

Создание конфигурационного файла

Создание SSL-сертификата

Для переключения сайта с HTTP на HTTPS нужно раскоментировать строки в конфигурации HTTP-домена и перегрузить Nginx.

Процесс разработки

Затем, на каком-то этапе, когда нужно выложить свои изменения в на тестовый сайт, можно залить изменения в репозиторий в ветку master — и изменения будут выложены в течении 2-5 минут.

Перед принятием Merge Request администратор должен убедиться, что коммиты в ветке разработчика идут строго после текущего положения ветки master основного репозитория. Автоматически в GitLab CE это сделать не получится, фича доступна только в GitLab EE.

Для выкатки изменений на рабочий сайт, нужно создать тэг release-. в Web-интерфейсе GitLab.

Вместе с изменением в коде проекта, разработчик может добавлять новые значения в параметры приложения. Значения этих параметров могут отличаться в зависимости от окружения.

Локальное окружение разработчика

Внутри Symfony эти значения попадают через файл app/config/parameters.yml (он также является частью приложения):

Для внедрения новых папаметров, нужно перезагрузить docker-compose :

Тестовый сайт разработчика

Staging

После принятия Merge Request и внедрения изменений на staging нужно добавить переменные во все остальные репозитории разработчиков.

Production

CI/CD изнутри

Загрузка зависимостей

PHPUnit-тестирование

Сборка

Здесь сборка для php-проекта — это создание docker-образов для контейнеров nginx и php, и выкладывание подготовленных образов в GitLab Container Registry.

Развёртывание

На данном этапе docker-образы приложения готовы и загружены в Container Registry. Осталось обновить приложения.

На удалённых серверах ceрвис phpmyadmin отсутствует; дополнительно к сервису php добавлен абсолютно такой же сервис spare ; а в конфигурации nginx вместо одного сервера в upstream прописано два. Использование двух одинаковых сервисов позволило добиться практически нулевого deployment downtime.

Алгоритм развёртывания следующий:

Заключение

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *