One place for hosting & domains

      Automating

      Automating Server Setup with Ansible: Набор материалов для тренинга DigitalOcean


      Материалы для проведения тренинга по автоматизации настройки сервера с помощью Ansible

      Данный набор материалов для тренинга предназначен для ознакомления технических специалистов с понятиями управления конфигурацией и использованием Ansible для автоматизации настройки инфраструктуры сервера.

      Его цель — предоставление полного набора ресурсов для докладчика при проведении мероприятия и выступления со вступительной речью, посвященной Ansible. Он включает следующее:

      • Слайды и заметки для докладчика, включая короткие демонстрационные видеоматериалы и команды для запуска вспомогательного демонстрационного рабочего приложения. Длительность доклада составляет примерно 50 минут.
      • Репозиторий GitHub, содержащий код демоприложения и необходимые скрипты Ansible для развертывания этого приложения на сервере Ubuntu.
      • Данное руководство, которое знакомит пользователя с процессом развертывания демоприложения Travellist на базе Laravel на удаленном сервере.

      Руководство предназначено для предоставления дополнительных данных и пояснений при обсуждении демоприложения. Оно также служит справочником для читателей, которые хотят развернуть приложение Laravel на удаленном сервере Ubuntu с помощью Ansible.

      Введение

      Автоматизация сервера сегодня играет важнейшую роль в системном администрировании, что вызвано расходной природой современных сред приложений. Инструменты управления конфигурацией, такие как Ansible, обычно используются для придания гибкости процессу автоматизации настройки сервера с помощью организации стандартных процедур для новых серверов. Это полезно для снижения вызванных человеческим фактором ошибок, связанных с ручной настройкой.

      Ansible предлагает упрощенную архитектуру, которая не требует установки специального программного обеспечения на узлах. Также он имеет широкий набор функций и встроенные модули, упрощающие написание скриптов автоматизации.

      Данное руководство, предназначенное для использования вместе со слайдами и замечаниями докладчика набора материалов для тренинга по автоматизации настройки сервера с помощью Ansible, демонстрирует, как настроить inventory-файл и выполнить набор скриптов для полной автоматизации процесса настройки удаленного сервера LEMP (Linux, ENginx, MariaDB и PHP-FPM) на Ubuntu 18.04, а также выполнить развертывание демонстрационного приложения Laravel для данной системы.

      Примечание. Этот материал предназначен для демонстрации использования плейбуков для автоматизации настройки сервера с помощью Ansible. Хотя наше демо включает приложение Laravel, запущенное на сервере LEMP, читатели могут вносить изменения и адаптировать указанную настройку согласно собственным потребностям.

      Предварительные требования

      Для данного обучающего руководства вам потребуется следующее:

      Шаг 1 — Клонирование репозитория с демо

      Прежде всего вам необходимо клонировать репозиторий со скриптами конфигурирования Ansible и демоприложением Laravel, которое мы будем развертывать на удаленных серверах. Все необходимые файлы можно найти в репозитории do-community/ansible-laravel-demo на Github.

      После входа на контрольный узел Ansible с помощью вашего пользователя sudo клонируйте репозиторий и перейдите в директорию, созданную командой git​​:

      • git clone https://github.com/do-community/ansible-laravel-demo.git
      • cd ansible-laravel-demo

      Теперь вы можете запустить команду ls для просмотра содержимого клонированного репозитория:

      • ls -l --group-directories-first

      Вывод будет выглядеть следующим образом:

      ansible-laravel-demo

      drwxrwxr-x 3 sammy sammy 4096 Mar 24 15:24 application
      drwxrwxr-x 2 sammy sammy 4096 Mar 24 15:24 group_vars
      drwxrwxr-x 7 sammy sammy 4096 Mar 24 15:24 roles
      -rw-rw-r-- 1 sammy sammy  102 Mar 24 15:24 inventory-example
      -rw-rw-r-- 1 sammy sammy 1987 Mar 24 15:24 laravel-deploy.yml
      -rw-rw-r-- 1 sammy sammy  794 Mar 24 15:24 laravel-env.j2
      -rw-rw-r-- 1 sammy sammy  920 Mar 24 15:24 readme.md
      -rw-rw-r-- 1 sammy sammy  318 Mar 24 15:24 server-setup.yml
      

      Ниже вы найдете описание каждой из этих папок и файлов и их значения:

      • application/: эта директория содержит демоприложение Laravel, которое будет развернуто на удаленном сервере к концу тренинга.
      • group_vars/: эта директория содержит файлы с переменными, содержащие пользовательские опции настройки приложения, такие как учетные данные базы данных и место хранения файлов приложения на удаленном сервере.
      • roles/: эта директория содержит различные роли Ansible, которые определяют конфигурацию LEMP-сервера на Ubuntu.
      • inventory-example: этот файл может использоваться в качестве основы для создания пользовательского inventory-файла для вашей инфраструктуры.
      • laravel-deploy.yml: этот плейбук будет выполнять развертывание демоприложения Laravel на удаленном сервере.
      • laravel-env.j2: этот шаблон используется плейбуком laravel-deploy.yml для настройки файла среды приложения.
      • readme.md: этот файл содержит общую информацию о конфигурации, содержащейся в этом репозитории.
      • server-setup.yml: этот плейбук будет выполнять конфигурацию сервера LEMP, используя роли, определенные в директории roles/.

      Шаг 2 — Настройка inventory-файла и тестирование подключения к узлам

      Теперь мы создадим inventory-файл для просмотра списка хостов, которые мы будем администрировать с помощью Ansible. Сначала скопируйте файл inventory-example в новый файл с именем hosts:

      • cp inventory-example hosts

      Теперь необходимо воспользоваться текстовым редактором по вашему выбору, чтобы открыть новый inventory-файл и обновить его на ваших серверах. Мы будем использовать nano:

      Пример inventory-файла, который входит в комплект материалов для тренинга, содержит две группы Ansible: dev и production. Это сделано для демонстрации использования переменных групп для настройки развертывания в разных средах. Если вы хотите протестировать эту настройку на отдельном узле, вы можете использовать группу dev или production и удалить другую группу из inventory-файла.

      ansible-laravel-demo/hosts

      [dev]
      203.0.113.0.101
      
      [prod]
      203.0.113.0.102
      
      [all:vars]
      ansible_python_interpreter=/usr/bin/python3
      

      Примечание. Переменная ansible_python_interpreter определяет путь к исполняемому файлу Python на удаленном хосте. Здесь мы просим Ansible задать эту переменную для всех хостов в этом inventory-файле.

      Сохраните и закройте файл после завершения. Если вы использовали nano, нажмите CTRL+X, а затем Y и ENTER для подтверждения.

      После внесения изменений в inventory-файл вы можете запустить модуль ping в Ansible для тестирования возможности подключения узла к хостам:

      • ansible all -i hosts -m ping -u root

      Давайте разберем эту команду:

      • all: эта опция просит Ansible запустить следующую команду для всех хостов из указанного inventory-файла.
      • -i hosts: указывает, какой inventory-файл необходимо использовать. Если эта опция не указана, Ansible будет пытаться использовать inventory-файл по умолчанию, который обычно находится в директории /etc/ansible/hosts.
      • -m ping: эта опция запускает модуль ping в Ansible, который будет тестировать подключение к узлам и проверять, находится ли исполняемый файл Python на удаленных системах.
      • -u root: этот опция указывает, какой удаленный пользователь должен использоваться для подключения к узлам. Здесь мы используем учетную запись root в качестве примера, поскольку это, как правило, единственная учетная запись, доступная на новых серверах. Другие опции подключения могут потребоваться в зависимости от поставщика инфраструктуры и конфигурации SSH.

      Если ваше SSH-подключение к узлам настроено корректно, вы получите следующий вывод:

      Output

      203.0.113.0.101 | SUCCESS => { "changed": false, "ping": "pong" } 203.0.113.0.102 | SUCCESS => { "changed": false, "ping": "pong" }

      Вывод pong означает, что ваш контрольный узел может подключаться к управляемым узлам и что Ansible может выполнять команды Python на удаленных хостах.

      Шаг 3 — Настройка файлов с переменными

      Перед запуском плейбуков, которые включены в этот комплект материалов для тренинга, вам необходимо будет сначала изменить файл с переменными, который содержит настройки, например, имя удаленного пользователя, которого необходимо создать, и учетные данные базы данных для настройки с помощью MariaDB.

      Откройте файл group_vars/all в используемом вами текстовом редакторе:

      ansible-laravel-demo/group_vars/all.yml

      ---
      # Initial Server Setup
      remote_user: sammy
      
      # MySQL Setup
      mysql_root_password: MYSQL_ROOT_PASSWORD
      mysql_app_db: travellist
      mysql_app_user: travellist_user
      mysql_app_pass: DB_PASSWORD
      
      # Web Server Setup
      http_host: "{{ ansible_facts.eth0.ipv4.address }}"
      remote_www_root: /var/www
      app_root_dir: travellist-demo
      document_root: "{{ remote_www_root }}/{{ app_root_dir }}/public"
      
      # Laravel Env Variables
      app_name: Travellist
      app_env: dev
      app_debug: true
      app_url: "http://{{ http_host }}"
      db_host: localhost
      db_port: 3306
      db_database: "{{ mysql_app_db }}"
      db_user: "{{ mysql_app_user }}"
      db_pass: "{{ mysql_app_pass }}"
      

      Вам необходимо обратить внимание на следующие переменные:

      • remote_user: указанный пользователь будет создан на удаленном сервере и получит привилегии sudo.
      • mysql_root_password: эта переменная определяет root-пароль базы данных для сервера MariaDB. Обратите внимание, что это должен быть защищенный пароль по вашему выбору.
      • mysql_app_db: имя базы данных, которую необходимо создать для приложения Laravel. Вам не обязательно изменять это значение, но вы можете сделать это, если хотите. Это значение будет использоваться для настройки файла конфигурации Laravel .env.
      • mysql_app_user: имя пользователя базы данных для приложения Laravel. Вам также не обязательно изменять это значение, но вы можете сделать это.
      • mysql_app_pass: пароль базы данных для приложения Laravel. Это должен быть защищенный пароль по вашему выбору.
      • http_host: доменное имя или IP-адрес удаленного хоста. Здесь мы используем факт Ansible, который содержит IPv4-адрес для сетевого интерфейса eth0. Если у вас есть доменные имена, указывающие на ваши удаленные хосты, вы можете создать отдельные файлы с переменными для каждого из них, перезаписав это значение, чтобы конфигурация Nginx содержала корректное имя хоста для каждого сервера.

      Когда вы закончите редактирование этих значений, сохраните и закройте файл.

      Создание дополнительных файлов с переменными для нескольких сред

      Если вы настроили ваш inventory-файл для нескольких узлов, вы, возможно, захотите создать дополнительные файлы с переменными для настройки каждого узла. В нашем примере inventory-файла мы создали две отдельные группы: dev и production. Чтобы избежать использования одних и тех же учетных данных базы данных и других настроек в двух средах, нам необходимо создать отдельный файл для хранения значений группы production.

      Вы, возможно, захотите скопировать файл с переменными по умолчанию и использовать его в качестве основы для ваших значений для группы production:

      • cp group_vars/all.yml group_vars/production.yml
      • nano group_vars/production.yml

      Поскольку файл all.yml содержит значения по умолчанию, которые будут корректными для всех сред, вы можете удалить все переменные, которые не будут изменены, в новом файле production.yml. Переменные, которые вам необходимо обновить для каждой среды, указаны здесь:

      ansible-laravel-demo/group_vars/production

      ---
      # Initial Server Setup
      remote_user: prod_user
      
      # MySQL Setup
      mysql_root_password: MYSQL_PROD_ROOT_PASSWORD
      mysql_app_pass: MYSQL_PROD_APP_PASSWORD
      
      # Laravel Env Variables
      app_env: prod
      app_debug: false
      

      Обратите внимание, что мы изменили значение app_env на prod и задали значение false для app_debug​​​. Это рекомендуемые настройки Laravel для среды production.

      После завершения настройки переменных для production сохраните и закройте файл.

      Шифрование файлов с переменными с помощью Ansible Vault

      Если вы захотите поделиться своей настройкой Ansible с другими пользователями, необходимо обеспечить безопасность учетных данных базы данных и других конфиденциальных данных в ваших файлах с переменными. Это можно сделать с помощью Ansible Vault, утилиты, которая поставляется с Ansible по умолчанию. Ansible Vault позволяет вам шифровать файлы с переменными, чтобы только пользователи с доступом к паролю Vault могли просматривать, изменять или расшифровывать эти файлы. Пароль Vault также требуется для запуска плейбука или команды, которые используют шифрованные файлы.

      Для шифрования вашего файла с переменными для production выполните следующую команду:

      • ansible-vault encrypt group_vars/production.yml

      Вам будет предложено ввести пароль Vault и подтвердить его. После этого, если вы решите просмотреть содержимое этого файла, вы увидите, что данные зашифрованы.

      Если вы хотите просмотреть файл с переменными, не изменяя его содержимое, воспользуйтесь командой view:

      • ansible-vault view group_vars/production.yml

      Вам будет предложено указать тот же пароль, который вы задали при шифровании этого файла с помощью ansible-vault. После предоставления пароля содержимое файла появится в вашем терминале. Чтобы закрыть просмотр файла, введите q.

      Для редактирования файла, который ранее был зашифрован с помощью Ansible Vault, используйте команду edit:

      • ansible-vault edit group_vars/production.yml

      Эта команда будет запрашивать пароль Vault для этого файла. Затем ваш редактор по умолчанию, поддерживающий работу в терминале, будет использован для открытия файла для редактирования. После внесения желаемых изменений сохраните и закройте файл, после чего он снова будет автоматически зашифрован в Ansible Vault​​​.

      Вы успешно завершили настройку ваших файлов с переменными. В следующем шаге мы запустим плейбук для настройки Nginx, PHP-FPM и MariaDB (которые, наряду с операционной системой на базе Linux, например Ubuntu, формируют стек LEMP) на вашем удаленном сервере (или серверах).

      Шаг 4 — Запуск плейбука LEMP

      Перед развертыванием демоприложения Laravel на удаленном сервере (серверах) нам необходимо настроить среду LEMP, которая будет обслуживать приложение. Плейбук server-setup.yml содержит роли Ansible, необходимые для настройки. Чтобы просмотреть его содержимое, выполните следующую команду:

      ansible-laravel-demo/server-setup.yml

      ---
      - hosts: all
        become: true
        roles:
          - { role: setup, tags: ['setup'] }
      
          - { role: mariadb, tags: ['mysql', 'mariadb', 'db', 'lemp'] }
      
          - { role: php, tags: ['php', 'web', 'php-fpm', 'lemp'] }
      
          - { role: nginx, tags: ['nginx', 'web', 'http', 'lemp'] }
      
          - { role: composer, tags: ['composer'] }
      

      Ниже вы найдете обзор всех ролей, включенных в этот плейбук:

      • setup: содержит задачи, необходимые для создания нового пользователя системы и предоставления ему привилегий sudo, а также активации брандмауэра ufw.
      • mariadb: устанавливает сервер базы данных MariaDB и создает базу данных приложения и пользователя.
      • php: устанавливает модули php-fpm и PHP, которые необходимы для запуска приложения Laravel.
      • nginx: устанавливает веб-сервер Nginx и разрешает доступ к порту 80.
      • composer: устанавливает Composer на глобальном уровне.

      Обратите внимание, что мы задали несколько тегов для каждой роли. Это нужно для перезапуска только отдельных частей данного плейбука, если возникнет такая необходимость. Если вы внесете изменения в ваш файл шаблонов Nginx, например, вам может понадобиться только перезапуск роли Nginx.

      Следующая команда будет запускать этот плейбук на всех серверах из вашего inventory-файла. --ask-vault-pass требуется только в случае, если вы использовали ansible-vault для шифрования файлов на предыдущем шаге:

      • ansible-playbook -i hosts server-setup.yml -u root --ask-vault-pass

      Вывод будет выглядеть следующим образом:

      Output

      PLAY [all] ********************************************************************************************** TASK [Gathering Facts] ********************************************************************************** ok: [203.0.113.0.101] ok: [203.0.113.0.102] TASK [setup : Install Prerequisites] ******************************************************************** changed: [203.0.113.0.101] changed: [203.0.113.0.102] ... RUNNING HANDLER [nginx : Reload Nginx] ****************************************************************** changed: [203.0.113.0.101] changed: [203.0.113.0.102] PLAY RECAP ********************************************************************************************** 203.0.113.0.101 : ok=31 changed=27 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1 203.0.113.0.102 : ok=31 changed=27 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1

      Теперь ваш узел (узлы) готов к обслуживанию приложений PHP с помощью Nginx+PHP-FPM и MariaDB в качестве сервера базы данных. В следующем шаге мы будем развертывать демоприложение Laravel, включенное в набор материалов, используя плейбук Ansible laravel-deploy.yml.

      Шаг 5 — Развертывание приложения Laravel

      Теперь, когда у вас есть рабочая среда LEMP на вашем удаленном сервере (серверах), вы можете запустить плейбук laravel-deploy.yml. Этот плейбук выполняет следующие задачи:

      1. Создание корневой директории документов приложения на удаленном сервере, если она еще не была создана.
      2. Синхронизация локальной папки приложения с удаленным сервером с помощью модуля sync.
      3. Настройка с помощью модуля acl разрешений для пользователя www-data при работе с папкой хранилища.
      4. Настройка приложения .env на основе шаблона laravel-env.j2.
      5. Установка зависимостей приложения с помощью Composer.
      6. Создание ключа безопасности приложения.
      7. Создание публичной ссылки для папки storage.
      8. Запуск процессов миграции и пополнения базы данных.

      Плейбук необходимо запускать с помощью пользователя non-root user с привилегиями sudo. Этот пользователь был создан при запуске плейбука server-setup.yml на предыдущем шаге, а его имя задано в переменной remote_user.

      Когда все будет готово, запустите плейбук laravel-deploy.yml с помощью следующей команды:

      • ansible-playbook -i hosts laravel-deploy.yml -u sammy --ask-vault-pass

      --ask-vault-pass требуется только в случае, если вы использовали ansible-vault для шифрования файлов на предыдущем шаге.

      Вывод будет выглядеть следующим образом:

      Output

      PLAY [all] ********************************************************************************************** TASK [Gathering Facts] ********************************************************************************** ok: [203.0.113.0.101] ok: [203.0.113.0.102] TASK [Make sure the remote app root exists and has the right permissions] ******************************* ok: [203.0.113.0.101] ok: [203.0.113.0.102] TASK [Rsync application files to the remote server] ***************************************************** ok: [203.0.113.0.101] ok: [203.0.113.0.102] ... TASK [Run Migrations + Seeders] ************************************************************************* ok: [203.0.113.0.101] ok: [203.0.113.0.102] PLAY RECAP ********************************************************************************************** 203.0.113.0.101 : ok=10 changed=9 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 203.0.113.0.102 : ok=10 changed=9 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

      После завершения выполнения команды вы сможете получить доступ к демоприложению, указав в браузере доменное имя или IP-адрес вашего узла:

      http://node_domain_or_IP
      

      Вы увидите подобную страницу:

      Демоприложение Travellist на базе Laravel

      Заключение

      Это обучающее руководство демонстрирует процесс настройки inventory-файла Ansible и подключения к удаленным узлам, а также запуск плейбуков Ansible для настройки сервера LEMP и развертывания на нем демоприложения Laravel. Данное руководство служит дополнением к слайдам и заметкам для докладчика из набора материалов для тренинга по автоматизации настройки сервера с помощью Ansible и использует репозиторий GitHub, содержащий все необходимые файлы для выполнения демонстрации в рамках тренинга.



      Source link

      Automating Server Setup with Ansible: Un kit d’atelier DigitalOcean


      ‘>Automatiser la mise en place du serveur avec les matériaux du kit de l’atelier

      Ce kit d’atelier est conçu pour aider un public technique à se familiariser avec les concepts de gestion de la configuration et à utiliser Ansible pour automatiser la configuration de l’infrastructure des serveurs. 

      L’objectif est de fournir un ensemble complet de ressources permettant à un conférencier d’organiser un événement et de présenter un exposé introductif sur Ansible. Il comprend :

      • Diapositives et notes de l’orateur y compris de courtes vidéos de démonstration et des commandes permettant d’exécuter une démo en direct facultative. Cet entretien dure environ 50 minutes.
      • Un dépôt GitHub contenant le code de l’application de démonstration et les scripts Ansible nécessaires pour déployer cette application sur un serveur Ubuntu.
      • Ce tutoriel, qui guide l’utilisateur dans le déploiement de la démo de Travellist de l’application Laravel sur un serveur distant.

      Ce tutoriel vise à compléter la démo de la conférence par des détails et des explications supplémentaires. Il sert également de référence pour les lecteurs qui cherchent à déployer une application Laravel sur un serveur Ubuntu distant en utilisant Ansible.

      Introduction

      L’automatisation des serveurs joue maintenant un rôle essentiel dans l’administration des systèmes, en raison de la nature disponible des environnements d’application modernes. Les outils de gestion de la configuration tels que Ansible sont généralement utilisés pour rationaliser le processus d’automatisation de la configuration des serveurs en établissant des procédures standard pour les nouveaux serveurs. Cela a l’avantage de réduire l’erreur humaine associée aux réglages manuels.

      Ansible offre une architecture simplifiée qui ne nécessite pas l’installation de logiciels spéciaux sur les nœuds. Elle fournit également un ensemble robuste de caractéristiques et de modules intégrés qui facilitent l’écriture de scripts d’automatisation.

      Ce tutoriel, conçu pour accompagner les diapositives et les notes de l’orateur pour le kit d’atelier Automatisation de la configuration du serveur avec Ansible vous montrera comment créer un fichier d’inventaire et exécuter un ensemble de scripts d’approvisionnement afin d’automatiser entièrement le processus de mise en place d’un serveur LEMP distant (Linux, (E) Nginx, MariaDB et PHP-FPM) sur Ubuntu 18.04 et de déployer une application Laravel de démonstration sur ce système. 

      Remarque: Ce matériel est destiné à démontrer comment utiliser des playbooks pour automatiser la configuration des serveurs avec Ansible. Bien que notre démo consiste en une application Laravel fonctionnant sur un serveur LEMP, les lecteurs sont encouragés à modifier et à adapter la configuration incluse pour répondre à leurs propres besoins.

      Conditions préalables

      Pour suivre ce tutoriel, vous aurez besoin de :

      • Un nœud de contrôle Ansible : une machine Ubuntu 18.04 avec Ansible installé et configuré pour se connecter à vos hôtes ansible en utilisant les clés SSH. Assurez-vous que le nœud de contrôle a un utilisateur régulier avec des permissions sudo et un pare-feu activé, comme expliqué dans notre Guide de configuration initiale du serveur, et un ensemble de Clés SSH. Pour configurer Ansible, veuillez suivre notre guide sur Comment installer et configurer Ansible sur Ubuntu 18.04.
      • Un ou plusieurs hôtes Ansible : un ou plusieurs serveurs Ubuntu 18.04 distants. Chaque hôte doit faire ajouter la clé publique du nœud de contrôle à son fichier authorized_keys comme expliqué dans l'Etape 2 de l'installation des clés SSH dans le guide Ubuntu 18.04. Au cas où vous utiliseriez les Droplets DigitalOcean en tant que nœuds, vous pouvez utiliser le panneau de commande pour ajouter votre clé publique à vos hôtes Ansible. 

      Étape 1 – Cloner le dépôt de démo

      La première chose que nous devons faire est de cloner le dépôt contenant les scripts de provisionnement Ansible et l’application de démonstration Laravel, que nous allons déployer sur les serveurs distants. Tous les fichiers nécessaires se trouvent dans le dépôt Github do-community/ansible-laravel-demo.

      Après vous être connecté à votre nœud de contrôle Ansible en tant qu’utilisateur sudo, clonez le dépôt et naviguez jusqu’au répertoire créé par la commande git :

      • git clone https://github.com/do-community/ansible-laravel-demo.git
      • cd ansible-laravel-demo

      Maintenant, vous pouvez exécuter une commande ls pour inspecter le contenu du référentiel cloné:

      • ls -l --group-directories-first

      Vous verrez une sortie de ce type :

      ansible-laravel-demo

      drwxrwxr-x 3 sammy sammy 4096 Mar 24 15:24 application
      drwxrwxr-x 2 sammy sammy 4096 Mar 24 15:24 group_vars
      drwxrwxr-x 7 sammy sammy 4096 Mar 24 15:24 roles
      -rw-rw-r-- 1 sammy sammy  102 Mar 24 15:24 inventory-example
      -rw-rw-r-- 1 sammy sammy 1987 Mar 24 15:24 laravel-deploy.yml
      -rw-rw-r-- 1 sammy sammy  794 Mar 24 15:24 laravel-env.j2
      -rw-rw-r-- 1 sammy sammy  920 Mar 24 15:24 readme.md
      -rw-rw-r-- 1 sammy sammy  318 Mar 24 15:24 server-setup.yml
      

      Voici un aperçu de chacun de ces dossiers et fichiers et de ce qu’ils sont :

      • application/: ce répertoire contient l’application Laravel de démonstration qui va être déployée sur le serveur distant à la fin de l’atelier. 
      • group_vars/: Ce répertoire contient des fichiers variables contenant des options personnalisées pour la configuration de l’application, telles que les informations d’identification de la base de données et l’endroit où stocker les fichiers de l’application sur le serveur distant. 
      • roles/: Ce répertoire contient les différents roles Ansible qui gèrent le provisionnement d’un serveur LEMP Ubuntu. 
      • inventory-example: Ce fichier peut être utilisé comme base pour créer un inventaire personnalisé de votre infrastructure. 
      • laravel-deploy.yml: Ce playbook permettra de déployer l’application Laravel de démonstration sur le serveur distant. 
      • laravel-env.j2: Ce modèle est utilisé par le playbook laravel-deploy.yml pour mettre en place le fichier d’environnement de l’application. 
      • readme.md: Ce fichier contient des informations générales sur le provisionnement contenu dans ce dépôt. 
      • server-setup.yml: Ce playbook fournira un serveur LEMP en utilisant les rôles définis dans le répertoire roles/. 

      Étape 2 – Mettre en place le fichier d’inventaire et test de la connexion aux nœuds

      Nous allons maintenant créer un fichier d’inventaire pour répertorier les hôtes que nous voulons gérer à l’aide d’Ansible. Tout d’abord, copiez le fichier inventory-example dans un nouveau fichier appelé hosts : 

      • cp inventory-example hosts

      Maintenant, utilisez l’éditeur de texte de votre choix pour ouvrir le nouveau fichier d’inventaire et le mettre à jour avec vos propres serveurs. Ici, nous utiliserons le nano :

      L’exemple d’inventaire fourni avec le kit d’atelier contient deux groupes d’Ansible : développement et production. Il s’agit de montrer comment utiliser des variables de groupe pour personnaliser le déploiement dans des environnements multiples. Si vous souhaitez tester cette configuration avec un seul nœud, vous pouvez utiliser soit le groupe de développement, soit le groupe de production et supprimer l’autre du fichier d’inventaire.

      ansible-laravel-demo/hosts

      [dev]
      203.0.113.0.101
      
      [prod]
      203.0.113.0.102
      
      [all:vars]
      ansible_python_interpreter=/usr/bin/python3
      

      Remarque : la variable ansible_python_interpreter définit le chemin vers l’exécutable Python sur l’hôte distant. Ici, nous disons à Ansible de définir cette variable pour tous les hôtes dans ce fichier d’inventaire.

      Enregistrez et fermez le fichier lorsque vous avez fini de le modifier. Si vous utilisez nano, vous pouvez le faire en appuyant sur CTRL+X, puis Y et ENTER (ENTRÉE) pour confirmer.

      Une fois que vous avez fini d’ajuster votre fichier d’inventaire, vous pouvez exécuter le module ping Ansible pour tester si le nœud de contrôle est capable de se connecter aux hôtes :

      • ansible all -i hosts -m ping -u root

      Décomposons cette commande :

      • all : Cette option indique à Ansible d’exécuter la commande suivante sur tous les hôtes du fichier d’inventaire désigné. 
      • -i hosts : Spécifie quel inventaire doit être utilisé. Lorsque cette option n’est pas disponible, Ansible s’efforcera d’utiliser l’inventaire par défaut, qui se trouve généralement à l’adresse /etc/ansible/hosts. 
      • -m ping : Cela permettra d’exécuter le ping Ansible qui testera la connectivité aux nœuds et déterminera si l’exécutable Python peut être trouvé ou non sur les systèmes distants. 
      • -u root : Cette option spécifie quel utilisateur distant doit être utilisé pour se connecter aux nœuds. Nous utilisons la root à titre d’exemple, car c’est généralement le seul compte disponible sur les nouveaux serveurs. D’autres options de connexion peuvent être nécessaires en fonction de votre fournisseur d’infrastructure et de la configuration SSH.

      Si votre connexion SSH aux nœuds est correctement configurée, vous obtiendrez le résultat suivant :

      Output

      203.0.113.0.101 | SUCCESS => { "changed": false, "ping": "pong" } 203.0.113.0.102 | SUCCESS => { "changed": false, "ping": "pong" }

      La réponse pong signifie que votre nœud de contrôle est capable de se connecter à vos nœuds gérés, et qu’Ansible est capable d’exécuter des commandes Python sur les hôtes distants.

      Étape 3 – Mettre en place les fichiers variables

      Avant de lancer les playbooks inclus dans ce kit d’atelier, vous devrez d’abord modifier le fichier de variables qui contient des paramètres tels que le nom de l’utilisateur distant à créer et les informations d’identification de la base de données à configurer avec MariaDB.

      Ouvrez le groupe_vars/all en utilisant l’éditeur de texte de votre choix : 

      ansible-laravel-demo/group_vars/all.yml

      ---
      # Initial Server Setup
      remote_user: sammy
      
      # MySQL Setup
      mysql_root_password: MYSQL_ROOT_PASSWORD
      mysql_app_db: travellist
      mysql_app_user: travellist_user
      mysql_app_pass: DB_PASSWORD
      
      # Web Server Setup
      http_host: "{{ ansible_facts.eth0.ipv4.address }}"
      remote_www_root: /var/www
      app_root_dir: travellist-demo
      document_root: "{{ remote_www_root }}/{{ app_root_dir }}/public"
      
      # Laravel Env Variables
      app_name: Travellist
      app_env: dev
      app_debug: true
      app_url: "http://{{ http_host }}"
      db_host: localhost
      db_port: 3306
      db_database: "{{ mysql_app_db }}"
      db_user: "{{ mysql_app_user }}"
      db_pass: "{{ mysql_app_pass }}"
      

      Les variables qui nécessitent votre attention sont :

      • remote_user : L’utilisateur spécifié sera créé sur le serveur distant et se verra accorder des privilèges sudo.
      • mysql_root_password: Cette variable définit le mot de passe de la root de la base de données pour le serveur MariaDB. Notez qu’il doit s’agir d’un mot de passe sécurisé que vous aurez choisi vous-même.
      • mysql_app_db: Le nom de la base de données à créer pour l’application Laravel. Vous n’avez pas besoin de changer cette valeur, mais vous êtes libre de le faire si vous le souhaitez. Cette valeur sera utilisée pour mettre en place le fichier de configuration Laravel .env.
      • mysql_app_user: Le nom de l’utilisateur de la base de données pour l’application Laravel. Là encore, vous n’êtes pas obligé de changer cette valeur, mais vous êtes libre de le faire.
      • mysql_app_pass: Le mot de passe de la base de données pour l’application Laravel. Il doit s’agir d’un mot de passe sécurisé de votre choix.
      • http_host: Le nom de domaine ou l’adresse IP de l’hôte distant. Ici, nous utilisons un fait Ansible qui contient l’adresse ipv4 pour l’interface réseau eth0. Si vos noms de domaine pointent vers vos hôtes distants, vous pouvez créer des fichiers variables séparés pour chacun d’eux, en écrasant cette valeur afin que la configuration Nginx contienne le nom d’hôte correct pour chaque serveur.

      Lorsque vous avez fini de modifier ces valeurs, enregistrez et fermez le fichier.

      Créer des fichiers variables supplémentaires pour des environnements multiples

      Si vous avez configuré votre fichier d’inventaire avec plusieurs nœuds, vous pouvez créer des fichiers variables supplémentaires pour configurer chaque nœud en conséquence. Dans notre exemple d’inventaire, nous avons créé deux groupes distincts : le développement et la production. Pour éviter d’avoir les mêmes références de base de données et autres paramètres dans les deux environnements, nous devons créer un fichier de variables séparé qui contiendra les valeurs de production.

      Vous voudrez peut-être copier le fichier de variables par défaut et l’utiliser comme base pour vos valeurs de production :

      • cp group_vars/all.yml group_vars/production.yml
      • nano group_vars/production.yml

      Comme le fichier all.yml contient les valeurs par défaut qui devraient être valables pour tous les environnements, vous pouvez supprimer du nouveau fichier production.yml toutes les variables qui n’auront pas besoin d’être modifiées. Les variables que vous devez mettre à jour pour chaque environnement sont mises en évidence ici :

      ansible-laravel-demo/group_vars/production

      ---
      # Initial Server Setup
      remote_user: prod_user
      
      # MySQL Setup
      mysql_root_password: MYSQL_PROD_ROOT_PASSWORD
      mysql_app_pass: MYSQL_PROD_APP_PASSWORD
      
      # Laravel Env Variables
      app_env: prod
      app_debug: false
      

      Remarquez que nous avons modifié la valeur app_env à prod et mis la valeur d’ app_debug à false. Il s’agit de paramètres Laravel recommandés pour les environnements de production.

      Une fois que vous avez fini de personnaliser vos variables de production, enregistrez et fermez le fichier.

      Crypter les fichiers variables avec Ansible Vault

      Si vous prévoyez de partager votre installation Ansible avec d’autres utilisateurs, il est important de préserver la sécurité des informations d’identification de la base de données et des autres données sensibles contenues dans vos fichiers variables. Cela est possible grâce à Ansible Vault, une fonctionnalité qui est incluse par défaut dans Ansible. Ansible Vault vous permet de crypter des fichiers variables afin que seuls les utilisateurs ayant accès au mot de passe de la chambre forte puissent voir, modifier ou décrypter ces fichiers. Le mot de passe de la chambre forte est également nécessaire pour exécuter un playbook ou une commande qui utilise des fichiers cryptés.

      Pour crypter votre fichier de variables de production, exécutez :

      • ansible-vault encrypt group_vars/production.yml

      Vous serez invité à fournir un mot de passe pour la chambre forte et à le confirmer. Une fois que vous aurez terminé, si vous vérifiez le contenu de ce fichier, vous verrez que les données sont maintenant cryptées.

      Si vous souhaitez visualiser le fichier de variables sans en modifier le contenu, vous pouvez utiliser la commande d'affichage : 

      • ansible-vault view group_vars/production.yml

      Vous serez invité à fournir le même mot de passe que celui que vous avez défini lors du cryptage de ce fichier avec ansible-vault. Après avoir fourni le mot de passe, le contenu du fichier apparaîtra dans votre terminal. Pour quitter la vue du fichier, tapez q.

      Pour modifier un fichier qui a été précédemment crypté avec Ansible Vault, utilisez la commande edit vault :

      • ansible-vault edit group_vars/production.yml

      Cette commande vous demandera de fournir le mot de passe de la chambre forte pour ce fichier. Votre éditeur de terminal par défaut sera alors utilisé pour ouvrir le fichier en vue de son édition. Après avoir effectué les modifications souhaitées, enregistrez et fermez le fichier, et il sera à nouveau automatiquement crypté par Ansible Vault.

      Vous avez maintenant terminé la configuration de vos fichiers variables. La prochaine étape consistera à mettre en place Nginx, PHP-FPM et MariaDB (qui, avec un système d’exploitation basé sur Linux comme Ubuntu, forment la pile LEMP) sur votre ou vos serveurs distants.

      Étape 4 – Exécuter le playbook LEMP

      Avant de déployer l’application Laravel de démonstration sur le(s) serveur(s) distant(s), nous devons mettre en place un environnement LEMP qui servira l’application. Le playbook serveur-setup.yml comprend les rôles Ansible nécessaires à la mise en place de ce système. Pour inspecter son contenu, exécutez :

      ansible-laravel-demo/server-setup.yml

      ---
      - hosts: all
        become: true
        roles:
          - { role: setup, tags: ['setup'] }
      
          - { role: mariadb, tags: ['mysql', 'mariadb', 'db', 'lemp'] }
      
          - { role: php, tags: ['php', 'web', 'php-fpm', 'lemp'] }
      
          - { role: nginx, tags: ['nginx', 'web', 'http', 'lemp'] }
      
          - { role: composer, tags: ['composer'] }
      

      Voici un aperçu de tous les rôles inclus dans ce playbook :

      • Installation : Contient les tâches nécessaires pour créer un nouvel utilisateur du système et lui accorder des privilèges sudo, ainsi qu’activer le pare-feu ufw. 
      • mariadb : Installe le serveur de base de données MariaDB et crée la base de données et l’utilisateur de l’application.
      • php : Installe les modules php-fpm et PHP qui sont nécessaires pour faire fonctionner une application Laravel.
      • nginx : Installe le serveur web Nginx et permet l’accès sur le port 80.
      • composer : Installe Composer globalement.

      Notez que nous avons mis en place quelques balises au sein de chaque rôle. Cette mesure vise à faciliter la réédition de certaines parties de ce manuel, si nécessaire. Si vous apportez des modifications à votre fichier modèle Nginx, par exemple, vous voudrez peut-être n’exécuter que le rôle Nginx.

      La commande suivante permet d’exécuter ce playbook sur tous les serveurs à partir de votre fichier d’inventaire. Le passe --ask-vault-pass n’est nécessaire que si vous avez utilisé ansible-vault pour crypter les fichiers variables à l’étape précédente : 

      • ansible-playbook -i hosts server-setup.yml -u root --ask-vault-pass

      Vous aurez une sortie similaire à celle-ci :

      Output

      PLAY [all] ********************************************************************************************** TASK [Gathering Facts] ********************************************************************************** ok: [203.0.113.0.101] ok: [203.0.113.0.102] TASK [setup : Install Prerequisites] ******************************************************************** changed: [203.0.113.0.101] changed: [203.0.113.0.102] ... RUNNING HANDLER [nginx : Reload Nginx] ****************************************************************** changed: [203.0.113.0.101] changed: [203.0.113.0.102] PLAY RECAP ********************************************************************************************** 203.0.113.0.101 : ok=31 changed=27 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1 203.0.113.0.102 : ok=31 changed=27 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1

      Votre ou vos nœuds sont maintenant prêts à servir des applications PHP en utilisant Nginx+PHP-FPM, avec MariaDB comme serveur de base de données. Dans une prochaine étape, nous déploierons l’application de démonstration Laravel incluse avec le playbook Ansible laravel-deploy.yml.

      Étape 5 – Déploiement de l’application Laravel

      Maintenant que vous avez un environnement LEMP fonctionnel sur votre ou vos serveurs distants, vous pouvez exécuter le playbook laravel-deploy.yml. Ce playbook permettra d’exécuter les tâches suivantes :

      1. Créez la racine du document d’application sur le serveur distant si elle n’a pas déjà été créée.
      2. Synchronisez le dossier d’application local avec le serveur distant à l’aide du module de synchronisation.
      3. Utilisez le module acl pour définir les autorisations pour l’utilisateur www-datapour le dossier de stockage. 
      4. Configurez le fichier d’application .env en se basant sur le modèle laravel-env.j2.
      5. Installez des dépendances d’application avec Composer.
      6. Générez la clé de sécurité de l’application.
      7. Établir un lien public pour le dossier de stockage. 
      8. Exécutez les migrations de bases de données et les seeders.

      Ce playbook doit être exécuté par un utilisateur non root avec des permissions sudo. Cet utilisateur doit avoir été créé lorsque vous avez exécuté le server-setup.yml playbook à l’étape précédente, en utilisant le nom défini par la variable remote_user. 

      Lorsque vous êtes prêt, lancez le playbook laravel-deploy.yml avec : 

      • ansible-playbook -i hosts laravel-deploy.yml -u sammy --ask-vault-pass

      Le passe --ask-vault-pass n’est nécessaire que si vous avez utilisé ansible-vault pour crypter les fichiers variables à l’étape précédente :

      Vous aurez une sortie similaire à celle-ci :

      Output

      PLAY [all] ********************************************************************************************** TASK [Gathering Facts] ********************************************************************************** ok: [203.0.113.0.101] ok: [203.0.113.0.102] TASK [Make sure the remote app root exists and has the right permissions] ******************************* ok: [203.0.113.0.101] ok: [203.0.113.0.102] TASK [Rsync application files to the remote server] ***************************************************** ok: [203.0.113.0.101] ok: [203.0.113.0.102] ... TASK [Run Migrations + Seeders] ************************************************************************* ok: [203.0.113.0.101] ok: [203.0.113.0.102] PLAY RECAP ********************************************************************************************** 203.0.113.0.101 : ok=10 changed=9 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 203.0.113.0.102 : ok=10 changed=9 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

      Lorsque l’exécution est terminée, vous pouvez accéder à l’application de démonstration en faisant pointer votre navigateur sur le nom de domaine ou l’adresse IP de votre nœud :

      http://node_domain_or_IP
      

      Vous verrez une page comme ceci :

      Démonstration de Laravel Travellist 

      Conclusion

      Ce tutoriel montre comment mettre en place un fichier d’inventaire Ansible et se connecter à des nœuds distants, et comment exécuter des playbooks Ansible pour mettre en place un serveur LEMP et y déployer une application de démonstration Laravel.Ce guide complète les diapositives et les notes de l’orateur du kit d’atelier sur l’automatisation de la configuration de serveur, et est accompagné d’une démo Dépôt GitHub contenant tous les fichiers nécessaires au suivi de la composante démo de cet atelier. 



      Source link

      Automating Server Setup with Ansible: A DigitalOcean Workshop Kit


      Automating Server Setup with Ansible Workshop Kit Materials

      This workshop kit is designed to help a technical audience become familiar with configuration management concepts and how to use Ansible to automate server infrastructure setup.

      The aim is to provide a complete set of resources for a speaker to host an event and deliver an introductory talk on Ansible. It includes:

      • Slides and speaker notes including short demo videos and commands for running an optional live demo. This talk runs for roughly 50 minutes.
      • A GitHub repository containing the demo app code and the necessary Ansible scripts to deploy that application to an Ubuntu server.
      • This tutorial, which walks a user through rolling out the Travellist demo Laravel application on a remote server.

      This tutorial is intended to supplement the talk demo with additional detail and elucidation. It also serves as a reference for readers seeking to deploy a Laravel application to a remote Ubuntu server using Ansible.

      Introduction

      Server automation now plays an essential role in systems administration, due to the disposable nature of modern application environments. Configuration management tools such as Ansible are typically used to streamline the process of automating server setup by establishing standard procedures for new servers. This has the benefit of reducing human error associated with manual setups.

      Ansible offers a simplified architecture that doesn’t require special software to be installed on nodes. It also provides a robust set of features and built-in modules which facilitate writing automation scripts.

      This tutorial, designed to accompany the Slides and speaker notes for the Automating Server Setup with Ansible Workshop Kit, will show you how to set up an inventory file and execute a set of provisioning scripts to fully automate the process of setting up a remote LEMP server (Linux, (E)Nginx, MariaDB and PHP-FPM) on Ubuntu 18.04 and to deploy a demo Laravel application to this system.

      Note: This material is intended to demonstrate how to use playbooks to automate server setup with Ansible. Although our demo consists of a Laravel application running on a LEMP server, readers are encouraged to modify and adapt the included setup to suit their own needs.

      Prerequisites

      To follow this tutorial, you will need:

      • One Ansible control node: an Ubuntu 18.04 machine with Ansible installed and configured to connect to your Ansible hosts using SSH keys. Make sure the control node has a regular user with sudo permissions and a firewall enabled, as explained in our Initial Server Setup guide, and a set of valid SSH keys. To set up Ansible, please follow our guide on How to Install and Configure Ansible on Ubuntu 18.04.
      • One or more Ansible Hosts: one or more remote Ubuntu 18.04 servers. Each host must have the control node’s public key added to its authorized_keys file, as explained in Step 2 of the How to Set Up SSH Keys on Ubuntu 18.04 guide. In case you are using DigitalOcean Droplets as nodes, you can use the control panel to add your public key to your Ansible hosts.

      Step 1 — Cloning the Demo Repository

      The first thing we need to do is clone the repository containing the Ansible provisioning scripts and the demo Laravel application that we’ll deploy to the remote servers. All the necessary files can be found at the do-community/ansible-laravel-demo Github repository.

      After logging in to your Ansible control node as your sudo user, clone the repository and navigate to the directory created by the git command:

      • git clone https://github.com/do-community/ansible-laravel-demo.git
      • cd ansible-laravel-demo

      Now, you can run an ls command to inspect the contents of the cloned repository:

      • ls -l --group-directories-first

      You’ll see output like this:

      ansible-laravel-demo

      drwxrwxr-x 3 sammy sammy 4096 Mar 24 15:24 application
      drwxrwxr-x 2 sammy sammy 4096 Mar 24 15:24 group_vars
      drwxrwxr-x 7 sammy sammy 4096 Mar 24 15:24 roles
      -rw-rw-r-- 1 sammy sammy  102 Mar 24 15:24 inventory-example
      -rw-rw-r-- 1 sammy sammy 1987 Mar 24 15:24 laravel-deploy.yml
      -rw-rw-r-- 1 sammy sammy  794 Mar 24 15:24 laravel-env.j2
      -rw-rw-r-- 1 sammy sammy  920 Mar 24 15:24 readme.md
      -rw-rw-r-- 1 sammy sammy  318 Mar 24 15:24 server-setup.yml
      

      Here’s an overview of each of these folders and files and what they are:

      • application/: This directory contains the demo Laravel application that is going to be deployed on the remote server by the end of the workshop.
      • group_vars/: This directory holds variable files containing custom options for the application setup, such as database credentials and where to store the application files on the remote server.
      • roles/: This directory contains the different Ansible roles that handle the provisioning of an Ubuntu LEMP server.
      • inventory-example: This file can be used as a base to create a custom inventory for your infrastructure.
      • laravel-deploy.yml: This playbook will deploy the demo Laravel application to the remote server.
      • laravel-env.j2: This template is used by the laravel-deploy.yml playbook to set up the application environment file.
      • readme.md: This file contains general information about the provisioning contained in this repository.
      • server-setup.yml: This playbook will provision a LEMP server using the roles defined in the roles/ directory.

      Step 2 — Setting Up the Inventory File and Testing Connection to Nodes

      We’ll now create an inventory file to list the hosts we want to manage using Ansible. First, copy the inventory-example file to a new file called hosts:

      • cp inventory-example hosts

      Now, use your text editor of choice to open the new inventory file and update it with your own servers. Here, we’ll use nano:

      The example inventory that comes with the workshop kit contains two Ansible groups: dev and production. This is meant to demonstrate how to use group variables to customize deployment in multiple environments. If you wish to test this setup with a single node, you can use either the dev or the production group and remove the other one from the inventory file.

      ansible-laravel-demo/hosts

      [dev]
      203.0.113.0.101
      
      [prod]
      203.0.113.0.102
      
      [all:vars]
      ansible_python_interpreter=/usr/bin/python3
      

      Note: the ansible_python_interpreter variable defines the path to the Python executable on the remote host. Here, we’re telling Ansible to set this variable for all hosts in this inventory file.

      Save and close the file when you’re done. If you are using nano, you can do that by hitting CTRL+X, then Y and ENTER to confirm.

      Once you’re done adjusting your inventory file, you can execute the ping Ansible module to test whether the control node is able to connect to the hosts:

      • ansible all -i hosts -m ping -u root

      Let’s break down this command:

      • all: This option tells Ansible to run the following command on all hosts from the designated inventory file.
      • -i hosts: Specifies which inventory should be used. When this option is not provided, Ansible will try to use the default inventory, which is typically located at /etc/ansible/hosts.
      • -m ping: This will execute the ping Ansible module, which will test connectivity to nodes and whether or not the Python executable can be found on the remote systems.
      • -u root: This option specifies which remote user should be used to connect to the nodes. We’re using the root account here as an example because this is typically the only account available on fresh new servers. Other connection options might be necessary depending on your infrastructure provider and SSH configuration.

      If your SSH connection to the nodes is properly set up, you’ll get the following output:

      Output

      203.0.113.0.101 | SUCCESS => { "changed": false, "ping": "pong" } 203.0.113.0.102 | SUCCESS => { "changed": false, "ping": "pong" }

      The pong response means your control node is able to connect to your managed nodes, and that Ansible is able to execute Python commands on the remote hosts.

      Step 3 — Setting Up Variable Files

      Before running the playbooks that are included in this workshop kit, you’ll first need to edit the variable file that contains settings such as the name of the remote user to create and the database credentials to set up with MariaDB.

      Open the group_vars/all file using your text editor of choice:

      ansible-laravel-demo/group_vars/all.yml

      ---
      # Initial Server Setup
      remote_user: sammy
      
      # MySQL Setup
      mysql_root_password: MYSQL_ROOT_PASSWORD
      mysql_app_db: travellist
      mysql_app_user: travellist_user
      mysql_app_pass: DB_PASSWORD
      
      # Web Server Setup
      http_host: "{{ ansible_facts.eth0.ipv4.address }}"
      remote_www_root: /var/www
      app_root_dir: travellist-demo
      document_root: "{{ remote_www_root }}/{{ app_root_dir }}/public"
      
      # Laravel Env Variables
      app_name: Travellist
      app_env: dev
      app_debug: true
      app_url: "http://{{ http_host }}"
      db_host: localhost
      db_port: 3306
      db_database: "{{ mysql_app_db }}"
      db_user: "{{ mysql_app_user }}"
      db_pass: "{{ mysql_app_pass }}"
      

      The variables that need your attention are:

      • remote_user: The specified user will be created on the remote server and granted sudo privileges.
      • mysql_root_password: This variable defines the database root password for the MariaDB server. Note that this should be a secure password of your own choosing.
      • mysql_app_db: The name of the database to create for the Laravel application. You don’t need to change this value, but you are free to do so if you wish. This value will be used to set up the .env Laravel configuration file.
      • mysql_app_user: The name of the database user for the Laravel application. Again, you are not required to change this value, but you are free to do so.
      • mysql_app_pass: The database password for the Laravel application. This should be a secure password of your choosing.
      • http_host: The domain name or IP address of the remote host. Here, we’re using an Ansible fact that contains the ipv4 address for the eth0 network interface. In case you have domain names pointing to your remote hosts, you may want to create separate variable files for each of them, overwriting this value so that the Nginx configuration contains the correct hostname for each server.

      When you are finished editing these values, save and close the file.

      Creating additional variable files for multiple environments

      If you’ve set up your inventory file with multiple nodes, you might want to create additional variable files to configure each node accordingly. In our example inventory, we have created two distinct groups: dev and production. To avoid having the same database credentials and other settings in both environments, we need to create a separate variable file to hold production values.

      You might want to copy the default variable file and use it as base for your production values:

      • cp group_vars/all.yml group_vars/production.yml
      • nano group_vars/production.yml

      Because the all.yml file contains the default values that should be valid for all environments, you can remove all the variables that won’t need changing from the new production.yml file. The variables that you should update for each environment are highlighted here:

      ansible-laravel-demo/group_vars/production

      ---
      # Initial Server Setup
      remote_user: prod_user
      
      # MySQL Setup
      mysql_root_password: MYSQL_PROD_ROOT_PASSWORD
      mysql_app_pass: MYSQL_PROD_APP_PASSWORD
      
      # Laravel Env Variables
      app_env: prod
      app_debug: false
      

      Notice that we’ve changed the app_env value to prod and set the app_debug value to false. These are recommended Laravel settings for production environments.

      Once you’re finished customizing your production variables, save and close the file.

      Encrypting variable files with Ansible Vault

      If you plan on sharing your Ansible setup with other users, it is important to keep the database credentials and other sensitive data in your variable files safe. This is possible with Ansible Vault, a feature that is included with Ansible by default. Ansible Vault allows you to encrypt variable files so that only users with access to the vault password can view, edit or unencrypt these files. The vault password is also necessary to run a playbook or a command that makes use of encrypted files.

      To encrypt your production variable file, run:

      • ansible-vault encrypt group_vars/production.yml

      You will be prompted to provide a vault password and confirm it. Once you’re finished, if you check the contents of that file, you’ll see that the data is now encrypted.

      If you want to view the variable file without changing its contents, you can use the view command:

      • ansible-vault view group_vars/production.yml

      You will be prompted to provide the same password you defined when encrypting that file with ansible-vault. After providing the password, the file’s contents will appear in your terminal. To exit the file view, type q.

      To edit a file that was previously encrypted with Ansible Vault, use the edit vault command:

      • ansible-vault edit group_vars/production.yml

      This command will prompt you to provide the vault password for that file. Your default terminal editor will then be used to open the file for editing. After making the desired changes, save and close the file, and it will be automatically encrypted again by Ansible Vault.

      You have now finished setting up your variable files. In the next step, we’ll run the playbook to set up Nginx, PHP-FPM, and MariaDB (which, along with a Linux-based operating system like Ubuntu, form the LEMP stack) on your remote server(s).

      Step 4 — Running the LEMP Playbook

      Before deploying the demo Laravel app to the remote server(s), we need to set up a LEMP environment that will serve the application. The server-setup.yml playbook includes the Ansible roles necessary to set this up. To inspect its contents, run:

      ansible-laravel-demo/server-setup.yml

      ---
      - hosts: all
        become: true
        roles:
          - { role: setup, tags: ['setup'] }
      
          - { role: mariadb, tags: ['mysql', 'mariadb', 'db', 'lemp'] }
      
          - { role: php, tags: ['php', 'web', 'php-fpm', 'lemp'] }
      
          - { role: nginx, tags: ['nginx', 'web', 'http', 'lemp'] }
      
          - { role: composer, tags: ['composer'] }
      

      Here’s an overview of all the roles included within this playbook:

      • setup: Contains the tasks necessary to create a new system user and grant them sudo privileges, as well as enabling the ufw firewall.
      • mariadb: Installs the MariaDB database server and creates the application database and user.
      • php: Installs php-fpm and PHP modules that are necessary in order to run a Laravel application.
      • nginx: Installs the Nginx web server and enables access on port 80.
      • composer: Installs Composer globally.

      Notice that we’ve set up a few tags within each role. This is to facilitate re-running only parts of this playbook, if necessary. If you make changes to your Nginx template file, for instance, you might want to run only the Nginx role.

      The following command will execute this playbook on all servers from your inventory file. The --ask-vault-pass is only necessary in case you have used ansible-vault to encrypt variable files in the previous step:

      • ansible-playbook -i hosts server-setup.yml -u root --ask-vault-pass

      You’ll get output similar to this:

      Output

      PLAY [all] ********************************************************************************************** TASK [Gathering Facts] ********************************************************************************** ok: [203.0.113.0.101] ok: [203.0.113.0.102] TASK [setup : Install Prerequisites] ******************************************************************** changed: [203.0.113.0.101] changed: [203.0.113.0.102] ... RUNNING HANDLER [nginx : Reload Nginx] ****************************************************************** changed: [203.0.113.0.101] changed: [203.0.113.0.102] PLAY RECAP ********************************************************************************************** 203.0.113.0.101 : ok=31 changed=27 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1 203.0.113.0.102 : ok=31 changed=27 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1

      Your node(s) are now ready to serve PHP applications using Nginx+PHP-FPM, with MariaDB as database server. In the next step, we’ll deploy the included demo Laravel app with the laravel-deploy.yml Ansible playbook.

      Step 5 — Deploying the Laravel Application

      Now that you have a working LEMP environment on your remote server(s), you can execute the laravel-deploy.yml playbook. This playbook will execute the following tasks:

      1. Create the application document root on the remote server, if it hasn’t already been created.
      2. Synchronize the local application folder to the remote server using the sync module.
      3. Use the acl module to set permissions for the www-data user on the storage folder.
      4. Set up the .env application file based on the laravel-env.j2 template.
      5. Install application dependencies with Composer.
      6. Generate application security key.
      7. Set up a public link for the storage folder.
      8. Run database migrations and seeders.

      This playbook should be executed by a non-root user with sudo permissions. This user should have been created when you executed the server-setup.yml playbook in the previous step, using the name defined by the remote_user variable.

      When you’re ready, run the laravel-deploy.yml playbook with:

      • ansible-playbook -i hosts laravel-deploy.yml -u sammy --ask-vault-pass

      The --ask-vault-pass is only necessary in case you have used ansible-vault to encrypt variable files in the previous step.

      You’ll get output similar to this:

      Output

      PLAY [all] ********************************************************************************************** TASK [Gathering Facts] ********************************************************************************** ok: [203.0.113.0.101] ok: [203.0.113.0.102] TASK [Make sure the remote app root exists and has the right permissions] ******************************* ok: [203.0.113.0.101] ok: [203.0.113.0.102] TASK [Rsync application files to the remote server] ***************************************************** ok: [203.0.113.0.101] ok: [203.0.113.0.102] ... TASK [Run Migrations + Seeders] ************************************************************************* ok: [203.0.113.0.101] ok: [203.0.113.0.102] PLAY RECAP ********************************************************************************************** 203.0.113.0.101 : ok=10 changed=9 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 203.0.113.0.102 : ok=10 changed=9 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

      When the execution is finished, you can access the demo application by pointing your browser to your node’s domain name or IP address:

      http://node_domain_or_IP
      

      You will see a page like this:

      Laravel Travellist Demo

      Conclusion

      This tutorial demonstrates how to set up an Ansible inventory file and connect to remote nodes, and how to run Ansible playbooks to set up a LEMP server and deploy a Laravel demo application to it. This guide compliments the Automating Server Setup with Ansible Workshop Kit’s slides and speaker notes, and is accompanied by a demo GitHub repository containing all necessary files to follow up with the demo component of this workshop.



      Source link