Как передать имя пользователя / config / main-local.php, host.password с помощью файла docker .gitlab-ci.yml? - PullRequest
0 голосов
/ 12 февраля 2019

Здесь я сделал все, как настроить свой инициализированный файл, используя php ./init --env=Development --overwrite=All на Ubuntu Server

#
# File is "indented" using multiple of 4 spaces
#
# Specify the docker image to use (only used if using docker runners)
# See: http://doc.gitlab.com/ee/ci/docker/using_docker_images.html
# From https://hub.docker.com/r/kaffineaddict/gitlabcakephp3/ - we could use  image: kaffineaddict/gitlabcakephp3
image: php:7.2

# The docker services to configure
# See: http://doc.gitlab.com/ee/ci/docker/using_docker_images.html#what-is-service
services:
    #- mysql:5.7

# Define custom build variables
#   For the default gitlab variables see: http://doc.gitlab.com/ce/ci/variables/README.html
#   These can be used below, or they will also be ENV variables available within' any scripts
#   you execute from the CI
variables:
    #MYSQL_DATABASE: site_zoova
    #MYSQL_ALLOW_EMPTY_PASSWORD: "1"
    #MYSQL_ROOT_PASSWORD: ThisIsAStrongPassword#^2

# Define commands that run before each job's script
before_script:
    - umask 022 # set permissions to default directory permissions of 755 and default file permissions are 644,
    # Install ssh-agent if not already installed, it is required by Docker.
    # (change apt-get to yum if you use a CentOS-based image)
    - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
    - docker-php-ext-install pdo pdo_mysql mysqli
    # Run ssh-agent (inside the build environment)
    - eval $(ssh-agent -s)

    # For Docker builds disable host key checking. Be aware that by adding that
    # you are suspectible to man-in-the-middle attacks.
    # WARNING: Use this only with the Docker executor, if you use it with shell
    # you will overwrite your user's SSH config.
    - mkdir -p ~/.ssh
    - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'

    # Prepare the build environment. A way to overcome this is to create a script which installs all prerequisites prior the actual testing is done.
    - bash ci/docker_install.sh > /dev/null
    #- bash ci/docker_install.sh
    # Prepare the build environment. A way to overcome this is to create a script which installs all prerequisites prior the actual testing is done.
    - cd $CI_PROJECT_DIR && curl --silent --show-error https://getcomposer.org/installer | php

    # Install composer dependencies
    #- composer install --no-plugins --no-scripts
    - cd $CI_PROJECT_DIR && php composer.phar config cache-files-dir /cache/composer
    - cd $CI_PROJECT_DIR && php composer.phar install --no-plugins --no-scripts --optimize-autoloader
    - cd $CI_PROJECT_DIR

    # Folder and file manipulation
    - 'which rsync || ( apt-get install rsync -y )'
    - '[ -d $CI_PROJECT_DIR/tmp ] || mkdir -p $CI_PROJECT_DIR/tmp'
    - rm -rf $CI_PROJECT_DIR/tmp/*
    - find $CI_PROJECT_DIR -type d -exec chmod 0755 {} \;
    - find $CI_PROJECT_DIR -type f -exec chmod 0644 {} \;
    - chmod -R 777 $CI_PROJECT_DIR/tmp
    - chmod +x $CI_PROJECT_DIR/ci/*
    - chown www-data:www-data $CI_PROJECT_DIR/ -R
    # Make sure these dirs/files are not writable
    # setup application
    - chmod go-w $CI_PROJECT_DIR
    - |
        # following 4 will done once on the server
        # cp common/config/main-local.example common/config/main-local.php
        # cp common/config/params.example common/config/params.php
        # cp rest/web/index.example rest/web/index.php

        #genetraing files and added to z_rsync_exclude_list
        php ./init --env=Development --overwrite=All
        php composer.phar update 
        yes | php yii migrate

        #resolve errors through phpcs
        # php ./vendor/bin/phpcs --encoding=utf-8 --extensions=php backend --colors
        # php ./vendor/bin/phpcs --encoding=utf-8 --extensions=php common --colors
        # php ./vendor/bin/phpcs --encoding=utf-8 --extensions=php rest --colors

        mkdir -p backend/web/assets
        chmod 775 backend/web/assets
        sudo chown www-data:www-data backend/web/assets
    - |
# Define commands that run before after all builds
after_script:
    #- find . -type d -exec chmod 0755 {} \; # Set directory permissions #moved in each stage
    #- find . -type f -exec chmod 0644 {} \; # Set file permissions #moved in each stage


# Define list of files that should be cached between subsequent runs -
# Composer stores all downloaded packages in the vendor/ directory.
# temporary commented out - builds failed
cache:
    paths:
        - vendor/

# stages is used to define build stages that can be used by jobs
# The specification of stages allows for having flexible multi stage pipelines
# The next stage only executes if all elements of the previous stage succeed
# Typically used for compiled languages testing and/or to automate deployments
stages:
    - development
    - production

#
# Run test on all branches but master
#
development:
    stage: development
    only:
        - dev
    script:
        - echo Running dev
        # DO NOT COPY THIS KEY TO PUBLIC PLACES
        - ssh-add <(echo "$SSH_PRIVATE_KEY_DEV")
        #- echo Running tests...
        # Ex: - phpunit --configuration phpunit_myapp.xml
        #- vendor/bin/phpunit # TODO: uncomment me - in docker file we have it as /usr/local/bin/phpunit
        # Sync the files to the server
        - echo Using rsync to push changes to dev server...
        - rsync -ap --stats -e "ssh -p $SSH_PORT_DEV" --exclude-from 'ci/z_rsync_exclude_list.txt' $CI_PROJECT_DIR/ $SSH_USER_DEV@$SSH_IP_DEV:$PROJECT_PATH_DEV
        - echo Running shell scripts on remote server
        - ssh -t -p $SSH_PORT_DEV $SSH_USER_DEV@$SSH_IP_DEV 'cd '"'$PROJECT_PATH_DEV'"';ci/shell-scripts-dev.sh'
        # Done
        - echo Done pushing changes to dev...
        #Environment is used to define that a job deploys to a specific environment. This allows easy tracking of all deployments to your environments straight from GitLab.
        #If environment is specified and no environment under that name exists, a new one will be created automatically.

    environment: development
        #Make sure we don't push to live if build has failed
    allow_failure: false #default behaviour

#
# Send to live server if branch is master
#
production:
    stage: production
    only:
        - master
    script:
        - echo Running prod
        # DO NOT COPY THIS KEY TO PUBLIC PLACES
        - ssh-add <(echo "$SSH_PRIVATE_KEY_PROD")
        #- echo Running tests...
        # Ex: - phpunit --configuration phpunit_myapp.xml
        #- vendor/bin/phpunit #TODO: uncomment me - in docker file we have it as /usr/local/bin/phpunit
        # Push to live server now
        - echo Using rsync to push changes to live server...
        - rsync -ap --stats -e "ssh -p $SSH_PORT_PROD" --exclude-from 'ci/z_rsync_exclude_list.txt' $CI_PROJECT_DIR/ $SSH_USER_PROD@$SSH_IP_PROD:$PROJECT_PATH_PROD
        - echo Running shell scripts on remote server
        - ssh -t -p $SSH_PORT_PROD $SSH_USER_PROD@$SSH_IP_PROD 'cd '"'$PROJECT_PATH_PROD'"';ci/shell-scripts-prod.sh'
        # Done
        - echo Done pushing changes to live...
    #Environment is used to define that a job deploys to a specific environment. This allows easy tracking of all deployments to your environments straight from GitLab.
    #If environment is specified and no environment under that name exists, a new one will be created automatically.
    environment: production
    ##make sure development built before moving to production
    dependencies:
        - development

Здесь возвращается ошибка Yii migrate Исключение 'yii \ base \ InvalidConfigException' с сообщением'Connection :: dsn не может быть пустым.'

Как я могу поддерживать его для разработки и производства

Примечание: я использую git lab ci contai ci / shell-scripts-dev.sh, ci / shell-scripts-prod.sh, ci / docker_install.sh

1 Ответ

0 голосов
/ 12 февраля 2019

Кажется, что вы неправильно анализируете локальные переменные env в своей конфигурации Yii. Необходимо убедиться, что файлы среды содержат некоторую ссылку на эти переменные

    <?php
    return [
        'components' => [
            // uncomment the following to setup a local db or, any other db
            'db' => [
                'class' => 'yii\db\Connection',
                'dsn' => 'mysql:host={APP_DB_HOST};dbname={APP_DB_NAME}',
                'username' => '{APP_DB_USERNAME}',
                'password' => '{APP_DB_PASSWORD}',
                'charset' => 'utf8',
            ],
            // ...
        ],
    ];

Определите их в разделе переменныхвашего сценария APP_DB_HOST APP_DB_NAME APP_DB_USERNAME APP_DB_PASSWORD

После запуска php ./init --env=Development --overwrite=All вам просто нужно проанализировать все только что созданные локальные конфигурационные файлы и заменить заполнители ({APP_DB_NAME}) фактическими значениями, определенными ранее, используя команда SED

  sed -i "s/{APP_DB_HOST}/${APP_DB_HOST}/g" ${CI_PROJECT_DIR}/common/config/main-local.php
  sed -i "s/{APP_DB_NAME}/${APP_DB_NAME}/g" ${CI_PROJECT_DIR}/common/config/main-local.php
  sed -i "s/{APP_DB_USERNAME}/${APP_DB_USERNAME}/g" ${CI_PROJECT_DIR}/common/config/main-local.php
  sed -i "s/{APP_DB_PASSWORD}/${APP_DB_PASSWORD}/g" ${CI_PROJECT_DIR}/common/config/main-local.php
...