Browse Source

Copie du playbook install WP sur Alpine avant conversion en Debian + roles

Benoît Hubert 1 year ago
parent
commit
ccbf93424f

+ 26 - 0
2024-php-mysql/README.md

@@ -0,0 +1,26 @@
+## Erreurs rencontrées
+
+Run playbook:
+
+```
+ansible-playbook -i inventory/hosts playbooks/install_php_mysql.yml -K
+```
+
+### MariaDB déjà démarré
+
+```
+TASK [MariaDB setup] **********************************************************************************************************************
+fatal: [192.168.1.85]: FAILED! => {"changed": true, "cmd": ["/etc/init.d/mariadb", "setup"], "delta": "0:00:00.009031", "end": "2024-02-14 16:27:03.174459", "msg": "non-zero return code", "rc": 1, "start": "2024-02-14 16:27:03.165428", "stderr": " * mariadb: cannot `setup' as it has not been stopped", "stderr_lines": [" * mariadb: cannot `setup' as it has not been stopped"], "stdout": "", "stdout_lines": []}
+```
+
+Résolu en vérifiant si MariaDB est déjà up & running.
+
+
+### Module manquant pour mysql_db
+
+```
+ASK [create MySQL database] **************************************************************************************************************
+fatal: [192.168.1.85]: FAILED! => {"changed": false, "msg": "A MySQL module is required: for Python 2.7 either PyMySQL, or MySQL-python, or for Python 3.X mysqlclient or PyMySQL. Consider setting ansible_python_interpreter to use the intended Python version."}
+```
+
+Pas mal de modules à installer

+ 82 - 0
2024-php-mysql/ansible-tuto-chatgpt.md

@@ -0,0 +1,82 @@
+Certainly! Let's start with a concise Ansible tutorial that covers installing PHP and MySQL on a target host using Alpine or Debian Linux distributions. We'll also look into structuring this setup in an Ansible playbook, sharing the playbook, and managing secrets securely.
+
+### 1. Installing PHP + MySQL on a Target Host
+
+For this example, let's assume we're targeting a Debian-based system for simplicity. The approach for Alpine would be similar, but the package names and the package manager (`apk` instead of `apt`) would differ.
+
+First, you need to ensure Ansible is installed on your control machine (the machine from which you are running Ansible commands). You can install Ansible on most Linux distributions using the default package manager.
+
+#### Ansible Playbook Structure
+
+An Ansible playbook is a YAML file that describes the desired state of your target machines. Here is a basic example of a playbook (`install_php_mysql.yml`) that installs PHP and MySQL on a Debian-based system:
+
+```yaml
+---
+- name: Install PHP and MySQL on Debian-based systems
+  hosts: all
+  become: yes  # Use privilege escalation to become the root user
+  tasks:
+    - name: Update apt cache
+      ansible.builtin.apt:
+        update_cache: yes
+        cache_valid_time: 3600  # Update the cache if it's older than an hour
+
+    - name: Install PHP
+      ansible.builtin.apt:
+        name: php
+        state: present
+
+    - name: Install MySQL Server
+      ansible.builtin.apt:
+        name: mysql-server
+        state: present
+
+    - name: Start MySQL Service
+      ansible.builtin.service:
+        name: mysql
+        state: started
+        enabled: yes  # Ensure the MySQL service starts on boot
+```
+
+### 2. Structuring Your Playbook
+
+Your Ansible project can be structured as follows:
+
+```
+ansible-project/
+│
+├── inventory/
+│   └── hosts  # Your inventory file where you define your target machines
+│
+├── group_vars/
+│   └── all.yml  # Variables that apply to all hosts
+│
+└── playbooks/
+    └── install_php_mysql.yml  # Your playbook file
+```
+
+- **Inventory (`hosts`)**: Defines groups of hosts. An example entry for a Debian host would be:
+  ```
+  [debian_servers]
+  your_debian_server ansible_host=example.com
+  ```
+
+- **Group Vars (`all.yml`)**: Here, you can define variables that are common across all hosts. For example, you could define the PHP and MySQL versions you want to install.
+
+- **Playbook (`install_php_mysql.yml`)**: Contains the tasks to be performed, as shown above.
+
+### 3. Sharing Your Playbook
+
+To share your playbook, you can use a version control system like Git. Push your Ansible project to a repository on GitHub, GitLab, or Bitbucket. This makes it easy to version your infrastructure as code and collaborate with others.
+
+### 4. Storing Secrets
+
+For storing secrets like database passwords, Ansible provides a feature called Ansible Vault. With Ansible Vault, you can encrypt sensitive data, making it safe to store in version control.
+
+- **Creating an Encrypted File**: Use the `ansible-vault create <file_name>` command. For example, `ansible-vault create secrets.yml`.
+- **Editing an Encrypted File**: Use the `ansible-vault edit secrets.yml`.
+- **Using Encrypted Variables in Playbooks**: Reference them just like any other variable. Ansible decrypts them on the fly when running the playbook.
+
+When you run a playbook that uses Vault-encrypted files, you'll need to provide the Vault password. Use the `--ask-vault-pass` flag or store the password in a file and use the `--vault-password-file <file_name>` option.
+
+This tutorial gives you a basic framework to start with Ansible for deploying PHP and MySQL. You can expand on this by adding more roles, tasks, and optimizing your playbook structure as your infrastructure grows. If you have more specific needs or run into any issues, feel free to ask!

+ 2 - 0
2024-php-mysql/inventory/hosts

@@ -0,0 +1,2 @@
+[alpine_servers]
+192.168.1.85  ansible_ssh_user=alpine

+ 223 - 0
2024-php-mysql/playbooks/install_php_mysql.yml

@@ -0,0 +1,223 @@
+---
+- name: Install PHP and MySQL on Debian-based systems
+  hosts: all
+  become: yes # Use privilege escalation to become the root user
+  vars:
+    db_username: wordpress
+    db_password: wordpress
+    db_name: wordpress
+  tasks:
+    - name: Update apt cache
+      ansible.builtin.apk:
+        update_cache: yes
+
+    # These two will be needed to install mysqlclient
+    - name: Install gcc, mariadb-dev, pkgconfig and pip3
+      ansible.builtin.apk:
+        name:
+          - gcc # needed to compile
+          - python3-dev # needed to compile
+          - musl-dev
+          - mariadb-dev
+          - py3-pip
+          - pkgconfig
+        state: present
+
+    - name: Install PHP
+      ansible.builtin.apk:
+        name:
+          - php
+          - php-fpm
+          - php-iconv # for WordPress
+          - php-mysqli # for WordPress/MySQL
+          - php-phar # for wp-cli
+          - php-json # for wp-cli
+          - php-openssl # for wp-cli
+          - php-curl # for wp-cli
+        state: present
+
+    - name: Install curl
+      ansible.builtin.apk:
+        name: curl
+        state: present
+
+    - name: Check if WordPress exists in /var/www/wordpress
+      stat:
+        path: /var/www/wordpress
+      register: wordpress_dir
+
+    - name: Check if wp-config.php exists in /var/www/wordpress
+      stat:
+        path: /var/www/wordpress/wp-config.php
+      register: wp_config
+
+    # Only if wordpress_dir.stat.exists is false, download WordPress
+    - name: Install WordPress using curl
+      command: curl -o /tmp/wordpress.tar.gz https://wordpress.org/latest.tar.gz
+      args:
+        creates: /tmp/wordpress.tar.gz
+      when: wordpress_dir.stat.exists == False
+
+    # Unzip WordPress only if /var/www/wordpress doesn't exist
+    - name: Unzip WordPress
+      # ansible.builtin.unarchive:
+      command: tar -xzf /tmp/wordpress.tar.gz -C /var/www
+      when: wordpress_dir.stat.exists == False
+
+    - name: Install Nginx
+      ansible.builtin.apk:
+        name: nginx
+        state: present
+
+    - name: Install MariaDB Server
+      ansible.builtin.apk:
+        name: mariadb
+        state: present
+
+    - name: Install MariaDB Client Tools
+      ansible.builtin.apk:
+        name: mariadb-client
+        state: present
+
+    - name: Start Nginx Service
+      ansible.builtin.service:
+        name: nginx
+        state: started
+        enabled: yes # Ensure the MySQL service starts on boot
+
+    # Store mariadb status in a variable
+    # It'll be useful to conditionally run `/etc/init.d/mariadb setup`
+    - name: Check MariaDB status
+      command: rc-service mariadb status
+      register: mariadb_status
+      ignore_errors: yes
+
+    # # Echo 'MARIADB STARTED' if mariadb is running
+    # - name: Debug MariaDB status
+    #   ansible.builtin.debug:
+    #     msg: "MARIADB STARTED"
+    #   when: mariadb_status.stdout.find('started') != -1
+
+    # # Echo 'MARIADB STOPPED' if mariadb is NOT running
+    # - name: Debug MariaDB status
+    #   ansible.builtin.debug:
+    #     msg: "MARIADB STOPPED"
+    #   when: mariadb_status.stdout.find('started') == -1
+
+    # Problem I had: it failed here after 1st run
+    - name: MariaDB setup
+      command: /etc/init.d/mariadb setup
+      # run only if service is NOT running, that is, the output from
+      # `rc-service mariadb status` doesn't contain `started`
+      when: mariadb_status.stdout.find('started') == -1
+
+    - name: Start MariaDB Service
+      ansible.builtin.service:
+        name: mariadb
+        state: started
+        enabled: yes # Ensure the MariaDB service starts on boot
+
+    - name: Install mysqlclient
+      ansible.builtin.pip:
+        name: mysqlclient
+        state: present
+
+    - name: create MySQL database
+      mysql_db:
+        check_implicit_admin: yes
+        login_user: "{{ db_username }}"
+        login_password: "{{ db_password }}"
+        name: "{{ db_name }}"
+        encoding: utf8mb4
+        collation: utf8mb4_unicode_ci
+        state: present
+
+    - name: create MySQL user
+      mysql_user:
+        name: "{{ db_username }}"
+        password: "{{ db_password }}"
+        priv: "{{ db_name }}.*:ALL,GRANT"
+        state: present
+
+    - name: Downlownload wp salt config
+      command: curl https://api.wordpress.org/secret-key/1.1/salt/
+      register: wp_salt
+      when: wp_config.stat.exists == False
+
+    # Register wp-salt content as variable
+    # - name: Read wp-salt content
+    #   ansible.builtin.slurp:
+    #     src: /tmp/wp-salt
+    #   register: wp_salt
+
+    # Use variables from vars above and from wp_salt
+    - name: Create wp-config.php
+      ansible.builtin.template:
+        src: templates/wp-config-sample.php.j2
+        dest: /var/www/wordpress/wp-config.php
+        owner: root
+        group: root
+        mode: 0644
+      when: wp_config.stat.exists == False
+
+    # Check that default.conf.bak exists
+    - name: Check if default.conf.bak exists
+      ansible.builtin.stat:
+        path: /etc/nginx/http.d/default.conf.bak
+      register: default_conf_bak
+
+    # Backup nginx default vhost config if not already backed up
+    - name: Backup default Nginx vhost config
+      command: mv /etc/nginx/http.d/default.conf /etc/nginx/http.d/default.conf.bak
+      when: default_conf_bak.stat.exists == False
+
+    # Overwrite default vhost config with our own
+    - name: Write new vhost config
+      ansible.builtin.template:
+        src: templates/nginx-wordpress.conf.j2
+        dest: /etc/nginx/http.d/nginx-wordpress.conf
+        owner: root
+        group: root
+        mode: 0644
+
+    - name: Restart PHP-FPM
+      ansible.builtin.service:
+        name: php-fpm81
+        state: restarted
+        enabled: yes # Ensure the PHP-FPM service starts on boot
+
+    - name: Restart Nginx
+      ansible.builtin.service:
+        name: nginx
+        state: restarted
+        enabled: yes # Ensure the PHP-FPM service starts on boot
+
+    # Check if wp-cli exists
+    - name: Check if wp-cli exists
+      ansible.builtin.stat:
+        path: /usr/local/bin/wp
+      register: wp_cli
+
+    # Download WordPress CLI
+    - name: Download WordPress CLI
+      command: curl -o /usr/local/bin/wp https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
+      args:
+        creates: /usr/local/bin/wp
+      when: wp_cli.stat.exists == False
+
+    # Make WordPress CLI executable
+    - name: Make WordPress CLI executable
+      command: chmod +x /usr/local/bin/wp
+
+    # Check if WordPress is installed
+    - name: Check if WordPress is installed
+      command: wp core is-installed --path=/var/www/wordpress
+      register: wp_installed
+      ignore_errors: yes
+
+    # WP core install (cwd: /var/www/wordpress)
+    - name: Install WordPress
+      command: wp core install --url=192.168.1.85 --title=My\ Blog --admin_user=admin --admin_password=admin --admin_email=benoithubert@gmail.com
+      args:
+        chdir: /var/www/wordpress
+      when: wp_installed.rc != 0

+ 19 - 0
2024-php-mysql/playbooks/templates/nginx-wordpress.conf.j2

@@ -0,0 +1,19 @@
+# Vhost for nginx - WordPress on PHP 8.1 in Alpine
+
+server {
+    listen 80 default_server;
+    listen [::]:80 default_server;
+    root /var/www/wordpress;
+    index index.php;
+
+    location / {
+        try_files $uri $uri/ /index.php?$args;
+    }
+
+    location ~ \.php$ {
+        include fastcgi_params;
+        fastcgi_pass 127.0.0.1:9000;
+        fastcgi_index index.php;
+        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
+    }
+}

+ 89 - 0
2024-php-mysql/playbooks/templates/wp-config-sample.php.j2

@@ -0,0 +1,89 @@
+<?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:
+ *
+ * * Database settings
+ * * Secret keys
+ * * Database table prefix
+ * * ABSPATH
+ *
+ * @link https://wordpress.org/documentation/article/editing-wp-config-php/
+ *
+ * @package WordPress
+ */
+
+// ** Database settings - You can get this info from your web host ** //
+/** The name of the database for WordPress */
+define( 'DB_NAME', '{{ db_name }}' );
+
+/** Database username */
+define( 'DB_USER', '{{ db_username }}' );
+
+/** Database password */
+define( 'DB_PASSWORD', '{{ db_password }}' );
+
+/** Database hostname */
+define( 'DB_HOST', 'localhost' );
+
+/** Database charset to use in creating database tables. */
+define( 'DB_CHARSET', 'utf8mb4' );
+
+/** The database collate type. Don't change this if in doubt. */
+define( 'DB_COLLATE', 'utf8mb4_unicode_ci' );
+
+/**#@+
+ * 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
+ */
+{{ wp_salt.stdout }}
+
+/**#@-*/
+
+/**
+ * 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 documentation.
+ *
+ * @link https://wordpress.org/documentation/article/debugging-in-wordpress/
+ */
+define( 'WP_DEBUG', false );
+
+/* Add any custom values between this line and the "stop editing" line. */
+
+
+
+/* That's all, stop editing! Happy publishing. */
+
+/** Absolute path to the WordPress directory. */
+if ( ! defined( 'ABSPATH' ) ) {
+	define( 'ABSPATH', __DIR__ . '/' );
+}
+
+/** Sets up WordPress vars and included files. */
+require_once ABSPATH . 'wp-settings.php';