One place for hosting & domains

      Установка WordPress со стеком LAMP в Ubuntu 18.04


      Предыдущая версия данного обучающего руководства была написана Джастином Эллингвудом

      Введение

      WordPress — это самая популярная CMS (система управления контентов) в сети Интернет. Она позволяет вам легко настраивать блоги и веб-сайты, устанавливаемые поверх отвечающего за за серверную часть MySQL с поддержкой PHP. WordPress обладает невероятной адаптивностью и позволяет в кратчайшие сроки создать и запустить веб-сайт. После настройки практически все административные функции доступны через пользовательский веб-интерфейс.

      В этом руководстве мы сфокусируемся главным образом на создании экземпляра WordPress на стеке LAMP (Linux, Apache, MySQL и PHP) на сервере Ubuntu 18.04.

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

      Для выполнения этого обучающего руководства вам потребуется доступ к серверу Ubuntu 18.04.

      Вам нужно будет выполнить следующие действия перед выполнением инструкций из данного руководства:

      • Создайте пользователя sudo на вашем сервере: мы будем выполнять шаги из этого руководства, используя пользователя без прав root с привилегиями sudo. Вы можете создать пользователя с привилегиями sudo, следуя указаниям нашего Руководства по начальной настройке сервера Ubuntu 18.04.
      • Установите стек LAMP: WordPress требуется веб-сервер, база данных и PHP для корректной работы. Настройка стека LAMP (Linux, Apache, MySQL и PHP) позволяет удовлетворить все эти требования. Воспользуйтесь этим руководством для установки и настройки данного программного обеспечения.
      • Защитите ваш сайт с помощью SSL: WordPress обслуживает динамический контент и отвечает за аутентификацию и авторизацию пользователя. TLS/SSL — это технология, которая позволяет вам шифровать трафик с сайта для защиты вашего соединения. Способ настройки SSL зависит от того, есть ли у вашего сайта доменное имя.
        • Если у вас есть доменное имя… самым простым способом защиты вашего сайта будет использование Let’s Encrypt, который предоставляет бесплатные доверенные сертификаты. Воспользуйтесь нашим Руководством по Let’s Encrypt для Apache для выполнения настройки.
        • Если у вас нет домена… и вы просто используете данную конфигурацию для тестирования или в личных целях, вы можете использовать самоподписанный сертификат. Данный способ обеспечивает аналогичный тип шифрования, но без подтверждения домена. Воспользуйтесь нашим руководством по самоподписанным сертификатам SSL для Apache для настройки.

      Завершив выполнение действий по первоначальной настройке, выполните вход на ваш сервер с помощью пользователя sudo и перейдите к выполнению шагов ниже.

      Шаг 1 — Создание базы данных MySQL и пользователя для WordPress

      Первый шаг, который мы выполним, будет подготовительным. WordPress использует MySQL для управления и хранения сайта, а также информации пользователя. Мы уже установили MySQL, но нам нужно создать базу данных и пользователя, которые будет использовать WordPress.

      Выполните вход в учетную запись MySQL с правами root (адмнистративную запись), введя следующую команду:

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

      Сначала нам нужно создать отдельную базу данных, которую будет контролировать WordPress. Вы можете использовать любое название, но мы в этом руководстве будем использовать wordpress для простоты. Создайте базу данных для WordPress, введя следующую команду:

      • CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

      Примечание. Каждый оператор MySQL должен заканчиваться точкой с запятой (;). Убедитесь, что это правило не нарушено, если вы столкнетесь с какими-либо проблемами.

      Затем мы создадим отдельную учетную запись пользователя MySQL, которую будем использовать исключительно для работы с нашей новой базы данных. Создание баз данных и учетных записей с одной функцией является хорошей идеей с точки зрения управления и безопасности. В этом руководстве мы будем использовать имя wordpressuser. Вы можете использовать любое имя по вашему желанию.

      Мы создадим учетную запись, установим пароль и предоставим доступ к созданной нами базе данных. Для этого мы воспользуемся следующей командой: Не забудьте задать надежный для пользователя базы данных на этом шаге:

      • GRANT ALL ON wordpress.* TO 'wordpressuser'@'localhost' IDENTIFIED BY 'password';

      Теперь у вас есть база данных и учетная запись пользователя, которые созданы специально для WordPress. Нам нужно установить права, чтобы текущий экземпляр MySQL узнал о последних внесенных нами изменениях:

      Выйдите из MySQL, введя следующую команду:

      Шаг 2 — Установка дополнительных расширений PHP

      При настройке нашего стека LAMP нам требуется только минимальный набор расширений, чтобы реализовать коммуникацию PHP с MySQL. WordPress и многие плагины используют дополнительные расширения PHP.

      Мы можем загрузить и установить некоторые из самых популярных расширений PHP, которые будет использовать WordPress, введя следующую команду:

      • sudo apt update
      • sudo apt install php-curl php-gd php-mbstring php-xml php-xmlrpc php-soap php-intl php-zip

      Примечание. Каждый плагин WordPress имеет собственный набор требований. Для поддержки некоторых из них может потребоваться установка дополнительных пакетов PHP. Ознакомьтесь с документацией плагина для получения информации о требованиях к PHP. Если они доступны, их можно установить с помощью apt, как показано выше.

      Сейчас мы перезапустим Apache, чтобы загрузить эти новые расширения в следующем разделе. Если вы вернетесь на к этому шагу при установке дополнительных плагинов, введите следующую команду для перезагрузки Apache:

      • sudo systemctl restart apache2

      Шаг 3 — Настройка конфигурации Apache для получения доступа к переопределения и перезаписи .htaccess

      Теперь мы внесем несколько незначительных изменений в нашу конфигурацию Apache. Согласно руководствам по предварительным требованиям, у вас должен быть файл конфигурации для вашего сайта в директории /etc/apache2/sites-available. В качестве примера мы будем использовать /etc/apache2/sites-available/wordpress.conf, но вы должны использовать путь к вашему файлу конфигурации при необходимости.

      Также мы будем использовать /var/www/wordpress в качестве корневой директории для нашей установки WordPress. Вы должны корневой веб-узел, указанный в вашей собственной конфигурации.

      Примечание. Вы можете использовать конфигурацию /000-default.conf по умолчанию (с /var/www/html в качестве корневого веб-узла). Это допустимо, если вы собираетесь размещать только один веб-сайт на этом сервере. Если нет, рекомендуется разделить необходимую конфигурацию на логические части, по одному файлу на каждый сайт.

      Активация переопределения .htaccess

      В настоящее время использование файлов .htaccess отключено. WordPress и многие плагины WordPress активно используют эти файлы для манипуляций с поведением веб-сервера внутри директории.

      Откройте файл конфигурации Apache для вашего веб-сайта:

      • sudo nano /etc/apache2/sites-available/wordpress.conf

      Чтобы разрешить использование файлов .htaccess, нам нужно настроить директиву AllowOverride внутри блока Directory, которая будет указывать на корневую директорию документа. Добавьте следующий текстовый блок внутри блока VirtualHost в вашем файле конфигурации, убедившись, что вы используете правильный корневой веб-узел:

      /etc/apache2/sites-available/wordpress.conf

      <Directory /var/www/wordpress/>
          AllowOverride All
      </Directory>
      

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

      Активация модуля перезаписи

      Теперь мы сможем активировать mod_rewrite для использования постоянных ссылок в WordPress:

      Активация изменений

      Перед применением внесенных изменений убедитесь, что мы не допустили ошибки в синтаксисе:

      • sudo apache2ctl configtest

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

      Output

      AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message Syntax OK

      Если вы хотите скрыть верхнюю строку, добавьте директиву ServerName в ваш основной (глобальный) файл конфигурации Apache в /etc/apache2/apache2conf. Вместо ServerName вы можете использовать домен или IP-адрес вашего сервера. Это просто сообщение, которое не влияет на функциональность вашего сайта. Если вывод содержит Syntax OK, вы можете двигаться дальше.

      Перезапустите Apache для внесения изменений:

      • sudo systemctl restart apache2

      Теперь мы загрузим и настроим непосредственно WordPress.

      Шаг 4 — Загрузка WordPress

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

      Перейдите в директорию с возможностью записи и загрузите сжатый релиз, введя следующую команду:

      • cd /tmp
      • curl -O https://wordpress.org/latest.tar.gz

      Извлеките сжатый файл для создания структуры директории WordPress:

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

      Создайте файл, введя следующую команду:

      • touch /tmp/wordpress/.htaccess

      Мы также заменим имя примера файла конфигурации на имя файла, который на практике использует WordPress:

      • cp /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php

      Также мы создадим директорию upgrade, чтобы WordPress не испытывал проблем с разрешениями при попытке сделать это самостоятельно после обновления программного обеспечения:

      • mkdir /tmp/wordpress/wp-content/upgrade

      Теперь мы можем скопировать все содержимое директории в корневую директорию. Мы используем точку в конце директории источника, чтобы указать, что все находящиеся в директории файлы должны быть скопированы, включая скрытые файлы (например, созданный нами файл .htaccess):

      • sudo cp -a /tmp/wordpress/. /var/www/wordpress

      Шаг 5 — Настройка директории WordPress

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

      Настройка принадлежности и разрешений

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

      Для начала мы укажем принадлежность всех файлов пользователю и группе www-data. Именно этот пользователь используется веб-сервером Apache, а Apache потребуется выполнять чтение и запись файлов WordPress для обслуживания веб-сайта и выполнения автоматических обновлений.

      Обновите принадлежность с помощью команды chown:

      • sudo chown -R www-data:www-data /var/www/wordpress

      Теперь мы запустим две команды find для установки корректных разрешений для директорий и файлов WordPress:

      • sudo find /var/www/wordpress/ -type d -exec chmod 750 {} ;
      • sudo find /var/www/wordpress/ -type f -exec chmod 640 {} ;

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

      Настройка файла конфигурации WordPress

      Теперь нам нужно внести некоторые изменения в основной файл конфигурации WordPress.

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

      Чтобы получить безопасные значения из генератора секретных ключей WordPress, введите:

      • curl -s https://api.wordpress.org/secret-key/1.1/salt/

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

      Предупреждение! Важно каждый раз запрашивать уникальные значения. НЕ копируйте значения, приведенные ниже!

      Output

      define('AUTH_KEY', '1jl/vqfs<XhdXoAPz9 DO NOT COPY THESE VALUES c_j{iwqD^<+c9.k<J@4H'); define('SECURE_AUTH_KEY', 'E2N-h2]Dcvp+aS/p7X DO NOT COPY THESE VALUES {Ka(f;rv?Pxf})CgLi-3'); define('LOGGED_IN_KEY', 'W(50,{W^,OPB%PB<JF DO NOT COPY THESE VALUES 2;y&,2m%3]R6DUth[;88'); define('NONCE_KEY', 'll,4UC)7ua+8<!4VM+ DO NOT COPY THESE VALUES #`DXF+[$atzM7 o^-C7g'); define('AUTH_SALT', 'koMrurzOA+|L_lG}kf DO NOT COPY THESE VALUES 07VC*Lj*lD&?3w!BT#-'); define('SECURE_AUTH_SALT', 'p32*p,]z%LZ+pAu:VY DO NOT COPY THESE VALUES C-?y+K0DK_+F|0h{!_xY'); define('LOGGED_IN_SALT', 'i^/G2W7!-1H2OQ+t$3 DO NOT COPY THESE VALUES t6**bRVFSD[Hi])-qS`|'); define('NONCE_SALT', 'Q6]U:K?j4L%Z]}h^q7 DO NOT COPY THESE VALUES 1% ^qUswWgn+6&xqHN&%');

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

      Теперь откройте файл конфигурации WordPress:

      • sudo nano /var/www/wordpress/wp-config.php

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

      /var/www/wordpress/wp-config.php

      . . .
      
      define('AUTH_KEY',         'put your unique phrase here');
      define('SECURE_AUTH_KEY',  'put your unique phrase here');
      define('LOGGED_IN_KEY',    'put your unique phrase here');
      define('NONCE_KEY',        'put your unique phrase here');
      define('AUTH_SALT',        'put your unique phrase here');
      define('SECURE_AUTH_SALT', 'put your unique phrase here');
      define('LOGGED_IN_SALT',   'put your unique phrase here');
      define('NONCE_SALT',       'put your unique phrase here');
      
      . . .
      

      Удалите эти строки и добавьте значения, которые вы скопировали из командной строки:

      /var/www/wordpress/wp-config.php

      . . .
      
      define('AUTH_KEY',         'VALUES COPIED FROM THE COMMAND LINE');
      define('SECURE_AUTH_KEY',  'VALUES COPIED FROM THE COMMAND LINE');
      define('LOGGED_IN_KEY',    'VALUES COPIED FROM THE COMMAND LINE');
      define('NONCE_KEY',        'VALUES COPIED FROM THE COMMAND LINE');
      define('AUTH_SALT',        'VALUES COPIED FROM THE COMMAND LINE');
      define('SECURE_AUTH_SALT', 'VALUES COPIED FROM THE COMMAND LINE');
      define('LOGGED_IN_SALT',   'VALUES COPIED FROM THE COMMAND LINE');
      define('NONCE_SALT',       'VALUES COPIED FROM THE COMMAND LINE');
      
      . . .
      

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

      Еще одно изменение, которое нам нужно внести, — это настройка метода, который WordPress должен использовать для записи данных в файловой системе. Поскольку мы предоставили веб-серверу разрешение на запись там, где ему потребуется, мы можем прямо установить для метода записи значение «прямая». Если бы мы не внесли это изменение в текущие настройки, это привело бы к тому, что при выполнении некоторых действий WordPress будет запрашивать данные учетной записи для FTP.

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

      /var/www/wordpress/wp-config.php

      . . .
      
      define('DB_NAME', 'wordpress');
      
      /** MySQL database username */
      define('DB_USER', 'wordpressuser');
      
      /** MySQL database password */
      define('DB_PASSWORD', 'password');
      
      . . .
      
      define('FS_METHOD', 'direct');
      

      Сохраните файл и закройте его после завершения.

      Шаг 6 — Завершение установки через веб-интерфейс

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

      В адресной строке браузера введите доменное имя или открытый IP-адрес вашего сервера:

      https://server_domain_or_IP
      

      Выберите язык, который вы хотите использовать:

      Выбор языка WordPress

      После этого вы должны попасть на главную страницу настройки.

      Выберите имя для вашего сайта WordPress и имя пользователя (не рекомендуется использовать имя «admin» или что-то подобное в целях безопасности). Надежный пароль создается автоматически. Сохраните этот пароль или выберите другой надежный пароль.

      Введите адрес электронной почты и укажите, хотите ли вы, чтобы поисковые машины индексировали ваш сайт:

      Настройка установки WordPress

      При нажатии далее вы перейдете на страницу входа:

      Запрос входа в WordPress

      После входа вы перейдете в панель управления WordPress:

      Запрос входа в WordPress

      Заключение

      WordPress установлен и готов к использованию! Ниже представлены некоторые общие шаги по выбору параметров для постоянных ссылок для ваших постов (см. Настройка > Постоянные ссылки) или выбора новой темы (см. Внешний вид > Темы). Если вы впервые работаете с WordPress, краткое изучите интерфейс для знакомства с вашей новой CMS.



      Source link

      How to Use Ansible to Install and Set Up WordPress with LAMP on Ubuntu 18.04


      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 while also reducing human error associated with manual setups.

      Ansible offers a simple 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 guide explains how to use Ansible to automate the steps contained in our guide on How To Install WordPress with LAMP on Ubuntu 18.04. WordPress is the most popular CMS (content management system) on the internet, allowing users to set up flexible blogs and websites on top of a MySQL backend with PHP processing. After setup, almost all administration can be done through the web frontend.

      Prerequisites

      In order to execute the automated setup provided by the playbook we’re discussing in this guide, you’ll need:

      Before proceeding, you first need to make sure your Ansible control node is able to connect and execute commands on your Ansible host(s). For a connection test, please check step 3 of How to Install and Configure Ansible on Ubuntu 18.04.

      What Does this Playbook Do?

      This Ansible playbook provides an alternative to manually running through the procedure outlined in our guide on How To Install WordPress with LAMP on Ubuntu 18.04.

      Running this playbook will perform the following actions on your Ansible hosts:

      1. Install aptitude, which is preferred by Ansible as an alternative to the apt package manager.
      2. Install the required LAMP packages and PHP extensions.
      3. Create and enable a new Apache VirtualHost for the WordPress website.
      4. Enable the Apache rewrite (mod_rewrite) module.
      5. Disable the default Apache website.
      6. Set the password for the MySQL root user.
      7. Remove anonymous MySQL accounts and the test database.
      8. Create a new MySQL database and user for the WordPress website.
      9. Set up UFW to allow HTTP traffic on the configured port (80 by default).
      10. Download and unpack WordPress.
      11. Set up correct directory ownership and permissions.
      12. Set up the wp-config.php file using the provided template.

      Once the playbook has finished running, you will have a WordPress installation running on top of a LAMP environment, based on the options you defined within your configuration variables.

      How to Use this Playbook

      The first thing we need to do is obtain the WordPress on LAMP playbook and its dependencies from the do-community/ansible-playbooks repository. We need to clone this repository to a local folder inside the Ansible Control Node.

      In case you have cloned this repository before while following a different guide, access your existing ansible-playbooks copy and run a git pull command to make sure you have updated contents:

      • cd ~/ansible-playbooks
      • git pull

      If this is your first time using the do-community/ansible-playbooks repository, you should start by cloning the repository to your home folder with:

      • cd ~
      • git clone https://github.com/do-community/ansible-playbooks.git
      • cd ansible-playbooks

      The files we’re interested in are located inside the wordpress-lamp_ubuntu1804 folder, which has the following structure:

      wordpress-lamp_ubuntu1804
      ├── files
      │   ├── apache.conf.j2
      │   └── wp-config.php.j2
      ├── vars
      │   └── default.yml
      ├── playbook.yml
      └── readme.md
      

      Here is what each of these files are:

      • files/apache.conf.j2: Template file for setting up the Apache VirtualHost.
      • files/wp-config.php.j2: Template file for setting up WordPress’s configuration file.
      • vars/default.yml: Variable file for customizing playbook settings.
      • playbook.yml: The playbook file, containing the tasks to be executed on the remote server(s).
      • readme.md: A text file containing information about this playbook.

      We’ll edit the playbook’s variable file to customize its options. Access the wordpress-lamp_ubuntu1804 directory and open the vars/default.yml file using your command line editor of choice:

      • cd wordpress-lamp_ubuntu1804
      • nano vars/default.yml

      This file contains a few variables that require your attention:

      vars/default.yml

      ---
      #System Settings
      php_modules: [ 'php-curl', 'php-gd', 'php-mbstring', 'php-xml', 'php-xmlrpc', 'php-soap', 'php-intl', 'php-zip' ]
      
      #MySQL Settings
      mysql_root_password: "mysql_root_password"
      mysql_db: "wordpress"
      mysql_user: "sammy"
      mysql_password: "password"
      
      #HTTP Settings
      http_host: "your_domain"
      http_conf: "your_domain.conf"
      http_port: "80"
      

      The following list contains a brief explanation of each of these variables and how you might want to change them:

      • php_modules: An array containing PHP extensions that should be installed to support your WordPress setup. You don’t need to change this variable, but you might want to include new extensions to the list if your specific setup requires it.
      • mysql_root_password: The desired password for the root MySQL account.
      • mysql_db: The name of the MySQL database that should be created for WordPress.
      • mysql_user: The name of the MySQL user that should be created for WordPress.
      • mysql_password: The password for the new MySQL user.
      • http_host: Your domain name.
      • http_conf: The name of the configuration file that will be created within Apache.
      • http_port: HTTP port for this virtual host, where 80 is the default.

      Once you’re done updating the variables inside vars/default.yml, save and close this file. If you used nano, do so by pressing CTRL + X, Y, then ENTER.

      You’re now ready to run this playbook on one or more servers. Most playbooks are configured to be executed on every server in your inventory, by default. We can use the -l flag to make sure that only a subset of servers, or a single server, is affected by the playbook. We can also use the -u flag to specify which user on the remote server we’re using to connect and execute the playbook commands on the remote hosts.

      To execute the playbook only on server1, connecting as sammy, you can use the following command:

      • ansible-playbook playbook.yml -l server1 -u sammy

      You will get output similar to this:

      Output

      PLAY [all] ***************************************************************************************************************************** TASK [Gathering Facts] ***************************************************************************************************************** ok: [server1] TASK [Install prerequisites] *********************************************************************************************************** ok: [server1] … TASK [Download and unpack latest WordPress] ******************************************************************************************** changed: [server1] TASK [Set ownership] ******************************************************************************************************************* changed: [server1] TASK [Set permissions for directories] ************************************************************************************************* changed: [server1] TASK [Set permissions for files] ******************************************************************************************************* changed: [server1] TASK [Set up wp-config] **************************************************************************************************************** changed: [server1] RUNNING HANDLER [Reload Apache] ******************************************************************************************************** changed: [server1] RUNNING HANDLER [Restart Apache] ******************************************************************************************************* changed: [server1] PLAY RECAP ***************************************************************************************************************************** server1 : ok=22 changed=18 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

      Note: For more information on how to run Ansible playbooks, check our Ansible Cheat Sheet Guide.

      When the playbook is finished running, you can go to your web browser to finish WordPress’s installation from there.

      Navigate to your server’s domain name or public IP address:

      http://server_host_or_IP
      

      You will see a page like this:

      WordPress language selection page

      After selecting the language you’d like to use for your WordPress installation, you’ll be presented with a final step to set up your WordPress user and password so you can log into your control panel:

      WordPress Setup

      When you click ahead, you will be taken to a page that prompts you to log in:

      WP login prompt

      Once you log in, you will be taken to the WordPress administration dashboard:

      WP Admin Panel

      Some common next steps for customizing your WordPress installation include choosing the permalinks setting for your posts (can be found in Settings > Permalinks) and selecting a new theme (in Appearance > Themes).

      The Playbook Contents

      You can find the WordPress on LAMP server setup featured in this tutorial in the wordpress-lamp_ubuntu1804 folder inside the DigitalOcean Community Playbooks repository. To copy or download the script contents directly, click the Raw button towards the top of each script.

      The full contents of the playbook as well as its associated files are also included here for your convenience.

      vars/default.yml

      The default.yml variable file contains values that will be used within the playbook tasks, such as the database settings and the domain name to configure within Apache.

      vars/default.yml

      #System Settings
      php_modules: [ 'php-curl', 'php-gd', 'php-mbstring', 'php-xml', 'php-xmlrpc', 'php-soap', 'php-intl', 'php-zip' ]
      
      #MySQL Settings
      mysql_root_password: "mysql_root_password"
      mysql_db: "wordpress"
      mysql_user: "sammy"
      mysql_password: "password"
      
      #HTTP Settings
      http_host: "your_domain"
      http_conf: "your_domain.conf"
      http_port: "80"
      

      files/apache.conf.j2

      The apache.conf.j2 file is a Jinja 2 template file that configures a new Apache VirtualHost. The variables used within this template are defined in the vars/default.yml variable file.

      files/apache.conf.j2

      <VirtualHost *:{{ http_port }}>
         ServerAdmin webmaster@localhost
         ServerName {{ http_host }}
         ServerAlias www.{{ http_host }}
         DocumentRoot /var/www/{{ http_host }}
         ErrorLog ${APACHE_LOG_DIR}/error.log
         CustomLog ${APACHE_LOG_DIR}/access.log combined
      
         <Directory /var/www/{{ http_host }}>
               Options -Indexes
         </Directory>
      
         <IfModule mod_dir.c>
             DirectoryIndex index.php index.html index.cgi index.pl  index.xhtml index.htm
         </IfModule>
      
      </VirtualHost>
      

      files/wp-config.php.j2

      The wp-config.php.j2 file is another Jinja template, used to set up the main configuration file used by WordPress. The variables used within this template are defined in the vars/default.yml variable file. Unique authentication keys and salts are generated using a hash function.

      files/info.php.j2

      <?php
      /**
       * The base configuration for WordPress
       *
       * The wp-config.php creation script uses this file during the
       * installation. You don't have to use the web site, you can
       * copy this file to "wp-config.php" and fill in the values.
       *
       * This file contains the following configurations:
       *
       * * MySQL settings
       * * Secret keys
       * * Database table prefix
       * * ABSPATH
       *
       * @link https://codex.wordpress.org/Editing_wp-config.php
       *
       * @package WordPress
       */
      
      // ** MySQL settings - You can get this info from your web host ** //
      /** The name of the database for WordPress */
      define( 'DB_NAME', '{{ mysql_db }}' );
      
      /** MySQL database username */
      define( 'DB_USER', '{{ mysql_user }}' );
      
      /** MySQL database password */
      define( 'DB_PASSWORD', '{{ mysql_password }}' );
      
      /** MySQL hostname */
      define( 'DB_HOST', 'localhost' );
      
      /** Database Charset to use in creating database tables. */
      define( 'DB_CHARSET', 'utf8' );
      
      /** The Database Collate type. Don't change this if in doubt. */
      define( 'DB_COLLATE', '' );
      
      /** Filesystem access **/
      define('FS_METHOD', 'direct');
      
      /**#@+
       * Authentication Unique Keys and Salts.
       *
       * Change these to different unique phrases!
       * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
       * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
       *
       * @since 2.6.0
       */
      define( 'AUTH_KEY',         '{{ ansible_date_time.iso8601_micro | hash('sha256') }}' );
      define( 'SECURE_AUTH_KEY',  '{{ ansible_date_time.iso8601_micro | hash('sha256') }}' );
      define( 'LOGGED_IN_KEY',    '{{ ansible_date_time.iso8601_micro | hash('sha256') }}' );
      define( 'NONCE_KEY',        '{{ ansible_date_time.iso8601_micro | hash('sha256') }}' );
      define( 'AUTH_SALT',        '{{ ansible_date_time.iso8601_micro | hash('sha256') }}' );
      define( 'SECURE_AUTH_SALT', '{{ ansible_date_time.iso8601_micro | hash('sha256') }}' );
      define( 'LOGGED_IN_SALT',   '{{ ansible_date_time.iso8601_micro | hash('sha256') }}' );
      define( 'NONCE_SALT',       '{{ ansible_date_time.iso8601_micro | hash('sha256') }}' );
      
      /**#@-*/
      
      /**
       * WordPress Database Table prefix.
       *
       * You can have multiple installations in one database if you give each
       * a unique prefix. Only numbers, letters, and underscores please!
       */
      $table_prefix = 'wp_';
      
      /**
       * For developers: WordPress debugging mode.
       *
       * Change this to true to enable the display of notices during development.
       * It is strongly recommended that plugin and theme developers use WP_DEBUG
       * in their development environments.
       *
       * For information on other constants that can be used for debugging,
       * visit the Codex.
       *
       * @link https://codex.wordpress.org/Debugging_in_WordPress
       */
      define( 'WP_DEBUG', false );
      
      /* That's all, stop editing! Happy publishing. */
      
      /** Absolute path to the WordPress directory. */
      if ( ! defined( 'ABSPATH' ) ) {
          define( 'ABSPATH', dirname( __FILE__ ) . '/' );
      }
      
      /** Sets up WordPress vars and included files. */
      require_once( ABSPATH . 'wp-settings.php' );
      
      

      playbook.yml

      The playbook.yml file is where all tasks from this setup are defined. It starts by defining the group of servers that should be the target of this setup (all), after which it uses become: true to define that tasks should be executed with privilege escalation (sudo) by default. Then, it includes the vars/default.yml variable file to load configuration options.

      playbook.yml

      ---
      - hosts: all
        become: true
        vars_files:
          - vars/default.yml
      
        tasks:
          - name: Install prerequisites
            apt: name=aptitude update_cache=yes state=latest force_apt_get=yes
            tags: [ system ]
      
          - name: Install LAMP Packages
            apt: name={{ item }} update_cache=yes state=latest
            loop: [ 'apache2', 'mysql-server', 'python3-pymysql', 'php', 'php-mysql', 'libapache2-mod-php' ]
            tags: [ system ]
      
          - name: Install PHP Extensions
            apt: name={{ item }} update_cache=yes state=latest
            loop: "{{ php_modules }}"
            tags: [ system ]
      
        # Apache Configuration
          - name: Create document root
            file:
              path: "/var/www/{{ http_host }}"
              state: directory
              owner: "www-data"
              group: "www-data"
              mode: '0755'
            tags: [ apache ]
      
          - name: Set up Apache VirtualHost
            template:
              src: "files/apache.conf.j2"
              dest: "/etc/apache2/sites-available/{{ http_conf }}"
            notify: Reload Apache
            tags: [ apache ]
      
          - name: Enable rewrite module
            shell: /usr/sbin/a2enmod rewrite
            notify: Reload Apache
            tags: [ apache ]
      
          - name: Enable new site
            shell: /usr/sbin/a2ensite {{ http_conf }}
            notify: Reload Apache
            tags: [ apache ]
      
          - name: Disable default Apache site
            shell: /usr/sbin/a2dissite 000-default.conf
            notify: Restart Apache
            tags: [ apache ]
      
        # MySQL Configuration
          - name: Set the root password
            mysql_user:
              name: root
              password: "{{ mysql_root_password }}"
              login_unix_socket: /var/run/mysqld/mysqld.sock
            tags: [ mysql, mysql-root ]
      
          - name: Remove all anonymous user accounts
            mysql_user:
              name: ''
              host_all: yes
              state: absent
              login_user: root
              login_password: "{{ mysql_root_password }}"
            tags: [ mysql ]
      
          - name: Remove the MySQL test database
            mysql_db:
              name: test
              state: absent
              login_user: root
              login_password: "{{ mysql_root_password }}"
            tags: [ mysql ]
      
          - name: Creates database for WordPress
            mysql_db:
              name: "{{ mysql_db }}"
              state: present
              login_user: root
              login_password: "{{ mysql_root_password }}"
            tags: [ mysql ]
      
          - name: Create MySQL user for WordPress
            mysql_user:
              name: "{{ mysql_user }}"
              password: "{{ mysql_password }}"
              priv: "{{ mysql_db }}.*:ALL"
              state: present
              login_user: root
              login_password: "{{ mysql_root_password }}"
            tags: [ mysql ]
      
        # UFW Configuration
          - name: "UFW - Allow HTTP on port {{ http_port }}"
            ufw:
              rule: allow
              port: "{{ http_port }}"
              proto: tcp
            tags: [ system ]
      
        # WordPress Configuration
          - name: Download and unpack latest WordPress
            unarchive:
              src: https://wordpress.org/latest.tar.gz
              dest: "/var/www/{{ http_host }}"
              remote_src: yes
              creates: "/var/www/{{ http_host }}/wordpress"
            tags: [ wordpress ]
      
          - name: Set ownership
            file:
              path: "/var/www/{{ http_host }}"
              state: directory
              recurse: yes
              owner: www-data
              group: www-data
            tags: [ wordpress ]
      
          - name: Set permissions for directories
            shell: "/usr/bin/find /var/www/{{ http_host }}/wordpress/ -type d -exec chmod 750 {} \;"
            tags: [ wordpress ]
      
          - name: Set permissions for files
            shell: "/usr/bin/find /var/www/{{ http_host }}/wordpress/ -type f -exec chmod 640 {} \;"
            tags: [ wordpress ]
      
          - name: Set up wp-config
            template:
              src: "files/wp-config.php.j2"
              dest: "/var/www/{{ http_host }}/wordpress/wp-config.php"
            tags: [ wordpress ]
      
        handlers:
          - name: Reload Apache
            service:
              name: apache2
              state: reloaded
      
          - name: Restart Apache
            service:
              name: apache2
              state: restarted
      

      Feel free to modify these files to best suit your individual needs within your own workflow.

      Conclusion

      In this guide, we used Ansible to automate the process of installing and setting up a WordPress website with LAMP on an Ubuntu 18.04 server.

      If you’d like to include other tasks in this playbook to further customize your server setup, please refer to our introductory Ansible guide Configuration Management 101: Writing Ansible Playbooks.



      Source link

      How to Use Ansible to Install and Set Up LAMP on Ubuntu 18.04


      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 while also reducing human error associated with manual setups.

      Ansible offers a simple 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 guide explains how to use Ansible to automate the steps contained in our guide on How To Install Linux, Apache, MySQL and PHP (LAMP) on Ubuntu 18.04. A “LAMP” stack is a group of open-source software that is typically installed together to enable a server to host dynamic websites and web apps. This term is actually an acronym which represents the Linux operating system, with the Apache web server. The site data is stored in a MySQL database, and dynamic content is processed by PHP.

      Prerequisites

      In order to execute the automated setup provided by the playbook we’re discussing in this guide, you’ll need:

      Before proceeding, you first need to make sure your Ansible control node is able to connect and execute commands on your Ansible host(s). For a connection test, please check step 3 of How to Install and Configure Ansible on Ubuntu 18.04.

      What Does this Playbook Do?

      This Ansible playbook provides an alternative to manually running through the procedure outlined in our guide on How To Install Linux, Apache, MySQL and PHP (LAMP) on Ubuntu 18.04.

      Running this playbook will perform the following actions on your Ansible hosts:

      1. Install aptitude, which is preferred by Ansible as an alternative to the apt package manager.
      2. Install the required LAMP packages.
      3. Create a new Apache VirtualHost and set up a dedicated document root for that.
      4. Enable the new VirtualHost.
      5. Disable the default Apache website, when the disable_default variable is set to true.
      6. Set the password for the MySQL root user.
      7. Remove anonymous MySQL accounts and the test database.
      8. Set up UFW to allow HTTP traffic on the configured port (80 by default).
      9. Set up a PHP test script using the provided template.

      Once the playbook has finished running, you will have a web PHP environment running on top of Apache, based on the options you defined within your configuration variables.

      How to Use this Playbook

      The first thing we need to do is obtain the LAMP playbook and its dependencies from the do-community/ansible-playbooks repository. We need to clone this repository to a local folder inside the Ansible Control Node.

      In case you have cloned this repository before while following a different guide, access your existing ansible-playbooks copy and run a git pull command to make sure you have updated contents:

      • cd ~/ansible-playbooks
      • git pull

      If this is your first time using the do-community/ansible-playbooks repository, you should start by cloning the repository to your home folder with:

      • cd ~
      • git clone https://github.com/do-community/ansible-playbooks.git
      • cd ansible-playbooks

      The files we’re interested in are located inside the lamp_ubuntu1804 folder, which has the following structure:

      lamp_ubuntu1804
      ├── files
      │   ├── apache.conf.j2
      │   └── info.php.j2
      ├── vars
      │   └── default.yml
      ├── playbook.yml
      └── readme.md
      

      Here is what each of these files are:

      • files/info.php.j2: Template file for setting up a PHP test page on the web server’s root
      • files/apache.conf.j2: Template file for setting up the Apache VirtualHost.
      • vars/default.yml: Variable file for customizing playbook settings.
      • playbook.yml: The playbook file, containing the tasks to be executed on the remote server(s).
      • readme.md: A text file containing information about this playbook.

      We’ll edit the playbook’s variable file to customize the configurations of both MySQL and Apache. Access the lamp_ubuntu1804 directory and open the vars/default.yml file using your command line editor of choice:

      • cd lamp_ubuntu1804
      • nano vars/default.yml

      This file contains a few variables that require your attention:

      vars/default.yml

      ---
      mysql_root_password: "mysql_root_password"
      app_user: "sammy"
      http_host: "your_domain"
      http_conf: "your_domain.conf"
      http_port: "80"
      disable_default: true
      

      The following list contains a brief explanation of each of these variables and how you might want to change them:

      • mysql_root_password: The desired password for the root MySQL account.
      • app_user: A remote non-root user on the Ansible host that will be set as the owner of the application files.
      • http_host: Your domain name.
      • http_conf: The name of the configuration file that will be created within Apache.
      • http_port: HTTP port for this virtual host, where 80 is the default.
      • disable_default: Whether or not to disable the default website that comes with Apache.

      Once you’re done updating the variables inside vars/default.yml, save and close this file. If you used nano, do so by pressing CTRL + X, Y, then ENTER.

      You’re now ready to run this playbook on one or more servers. Most playbooks are configured to be executed on every server in your inventory, by default. We can use the -l flag to make sure that only a subset of servers, or a single server, is affected by the playbook. We can also use the -u flag to specify which user on the remote server we’re using to connect and execute the playbook commands on the remote hosts.

      To execute the playbook only on server1, connecting as sammy, you can use the following command:

      • ansible-playbook playbook.yml -l server1 -u sammy

      You will get output similar to this:

      Output

      PLAY [all] ********************************************************************************************************* TASK [Gathering Facts] *********************************************************************************************************ok: [server1] TASK [Install prerequisites] *********************************************************************************************************ok: [server1] => (item=aptitude) ... TASK [UFW - Allow HTTP on port 80] ********************************************************************************************************* changed: [server1] TASK [Sets Up PHP Info Page] ********************************************************************************************************* changed: [server1] RUNNING HANDLER [Reload Apache] ********************************************************************************************************* changed: [server1] RUNNING HANDLER [Restart Apache] ********************************************************************************************************* changed: [server1] PLAY RECAP ********************************************************************************************************* server1 : ok=15 changed=11 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

      Note: For more information on how to run Ansible playbooks, check our Ansible Cheat Sheet Guide.

      When the playbook is finished running, go to your web browser and access the host or IP address of the server, as configured in the playbook variables, followed by /info.php:

      http://server_host_or_IP/info.php
      

      You will see a page like this:

      phpinfo page

      Because this page contains sensitive information about your PHP environment, it is recommended that you remove it from the server by running an rm -f /var/www/info.php command once you have finished setting it up.

      The Playbook Contents

      You can find the LAMP server setup featured in this tutorial in the lamp_ubuntu1804 folder inside the DigitalOcean Community Playbooks repository. To copy or download the script contents directly, click the Raw button towards the top of each script.

      The full contents of the playbook as well as its associated files are also included here for your convenience.

      vars/default.yml

      The default.yml variable file contains values that will be used within the playbook tasks, such as the password for the MySQL root account and the domain name to configure within Apache.

      vars/default.yml

      ---
      mysql_root_password: "mysql_root_password"
      app_user: "sammy"
      http_host: "your_domain"
      http_conf: "your_domain.conf"
      http_port: "80"
      disable_default: true
      

      files/apache.conf.j2

      The apache.conf.j2 file is a Jinja 2 template file that configures a new Apache VirtualHost. The variables used within this template are defined in the vars/default.yml variable file.

      files/apache.conf.j2

      <VirtualHost *:{{ http_port }}>
         ServerAdmin webmaster@localhost
         ServerName {{ http_host }}
         ServerAlias www.{{ http_host }}
         DocumentRoot /var/www/{{ http_host }}
         ErrorLog ${APACHE_LOG_DIR}/error.log
         CustomLog ${APACHE_LOG_DIR}/access.log combined
      
         <Directory /var/www/{{ http_host }}>
               Options -Indexes
         </Directory>
      
         <IfModule mod_dir.c>
             DirectoryIndex index.php index.html index.cgi index.pl  index.xhtml index.htm
         </IfModule>
      
      </VirtualHost>
      

      files/info.php.j2

      The info.php.j2 file is another Jinja template, used to set up a test PHP script in the document root of the newly configured LAMP server.

      files/info.php.j2

      <?php
      phpinfo();
      
      

      playbook.yml

      The playbook.yml file is where all tasks from this setup are defined. It starts by defining the group of servers that should be the target of this setup (all), after which it uses become: true to define that tasks should be executed with privilege escalation (sudo) by default. Then, it includes the vars/default.yml variable file to load configuration options.

      playbook.yml

      
      ---
      - hosts: all
        become: true
        vars_files:
          - vars/default.yml
      
        tasks:
          - name: Install prerequisites
            apt: name={{ item }} update_cache=yes state=latest force_apt_get=yes
            loop: [ 'aptitude' ]
      
        #Apache Configuration
          - name: Install LAMP Packages
            apt: name={{ item }} update_cache=yes state=latest
            loop: [ 'apache2', 'mysql-server', 'python3-pymysql', 'php', 'php-mysql', 'libapache2-mod-php' ]
      
          - name: Create document root
            file:
              path: "/var/www/{{ http_host }}"
              state: directory
              owner: "{{ app_user }}"
              mode: '0755'
      
          - name: Set up Apache virtualhost
            template:
              src: "files/apache.conf.j2"
              dest: "/etc/apache2/sites-available/{{ http_conf }}"
            notify: Reload Apache
      
          - name: Enable new site
            shell: /usr/sbin/a2ensite {{ http_conf }}
            notify: Reload Apache
      
          - name: Disable default Apache site
            shell: /usr/sbin/a2dissite 000-default.conf
            when: disable_default
            notify: Reload Apache
      
        # MySQL Configuration
          - name: Sets the root password
            mysql_user:
              name: root
              password: "{{ mysql_root_password }}"
              login_unix_socket: /var/run/mysqld/mysqld.sock
      
          - name: Removes all anonymous user accounts
            mysql_user:
              name: ''
              host_all: yes
              state: absent
              login_user: root
              login_password: "{{ mysql_root_password }}"
      
          - name: Removes the MySQL test database
            mysql_db:
              name: test
              state: absent
              login_user: root
              login_password: "{{ mysql_root_password }}"
      
        # UFW Configuration
          - name: "UFW - Allow HTTP on port {{ http_port }}"
            ufw:
              rule: allow
              port: "{{ http_port }}"
              proto: tcp
      
        # PHP Info Page
          - name: Sets Up PHP Info Page
            template:
              src: "files/info.php.j2"
              dest: "/var/www/{{ http_host }}/info.php"
      
        handlers:
          - name: Reload Apache
            service:
              name: apache2
              state: reloaded
      
          - name: Restart Apache
            service:
              name: apache2
              state: restarted
      

      Feel free to modify these files to best suit your individual needs within your own workflow.

      Conclusion

      In this guide, we used Ansible to automate the process of installing and setting up a LAMP environment on a remote server. Because each individual typically has different needs when working with MySQL databases and users, we encourage you to check out the official Ansible documentation for more information and use cases of the mysql_user Ansible module.

      If you’d like to include other tasks in this playbook to further customize your server setup, please refer to our introductory Ansible guide Configuration Management 101: Writing Ansible Playbooks.



      Source link