Benoît Hubert 1 年間 前
コミット
b088702b04

+ 4 - 0
README.md

@@ -0,0 +1,4 @@
+# Playbooks Ansible pour déploiement LEMP + WordPress
+
+- sans rôles : `lemp-wordpress/`
+- avec rôles : `lemp-wordpress-with-roles/` - [explication sur les rôles](lemp-wordpress-with-roles/roles.md)

+ 0 - 266
ansible-initial-debian-setup/README.md

@@ -1,266 +0,0 @@
-# Setup initial Debian 12 avec Ansible
-
-> Contexte :
->
-> - On vient d'installer une debian 12.5 sans rien.
-> - On veut automatiser la création de comptes utilisateurs
-
-Mes deux hosts sur le LAN sont :
-
-- debian-111 : 192.168.1.18
-- debian-112 : 192.168.1.85
-- debian-113 : 192.168.1.109
-
-## Etapes
-
-- Création `inventory.ini` avec les deux hosts.
-- Création playbook qui va
-
-  - installer sudo
-  - créer des utilisateurs avec droits sudo
-
-## NOTE sur utilisation macOS comme _control node_
-
-Voir `ansible-macos-control-node/README.md`.
-
-On va utiliser une VM debian comme control node.
-
-## Setup control node Debian 12.5
-
-### Install Ansible
-
-Mon control node est `192.168.1.181`.
-
-- `su -` (pas encore installé `sudo`)
-- `apt install gnupg curl`
-- les commandes données dans la [doc officielle pour l'install sur Debian](https://docs.ansible.com/ansible/latest/installation_guide/installation_distros.html#installing-ansible-on-debian) ne **marchent pas**
-- `curl -o ansible.gpg "https://keyserver.ubuntu.com/pks/lookup?fingerprint=on&op=get&search=0x6125E2A8C77F2818FB7BD15B93C4A3FD7BB9C367"`
-- `gpg --dearmour -o /usr/share/keyrings/ansible-archive-keyring.gpg ansible.gpg` (toujours comme `root`)
-- `echo "deb [signed-by=/usr/share/keyrings/ansible-archive-keyring.gpg] http://ppa.launchpad.net/ansible/ansible/ubuntu $UBUNTU_CODENAME main" | tee /etc/apt/sources.list.d/ansible.list`
-- `apt update`
-- `apt install -y ansible`
-
-MIEUX de tout faire en `sudo` je suppose. On va aussi installer `etckeeper`.
-
-### Install Git et clone repo...
-
-... où j'ai ma config `ansible.cfg` et mon `inventory.ini`.
-
-## D'abord commandes ad-hoc pour tester
-
-### Ping
-
-```
-$ ansible -i ./inventory.ini all -m ping -u debian -k
-SSH password:
-192.168.1.18 | SUCCESS => {
-    "ansible_facts": {
-        "discovered_interpreter_python": "/usr/bin/python3"
-    },
-    "changed": false,
-    "ping": "pong"
-}
-192.168.1.85 | SUCCESS => {
-    "ansible_facts": {
-        "discovered_interpreter_python": "/usr/bin/python3"
-    },
-    "changed": false,
-    "ping": "pong"
-}
-192.168.1.109 | SUCCESS => {
-    "ansible_facts": {
-        "discovered_interpreter_python": "/usr/bin/python3"
-    },
-    "changed": false,
-    "ping": "pong"
-}
-
-```
-
-### `setup`
-
-```
-ansible -i ./inventory.ini all -m setup -k
-```
-
-Produit une _énorme_ sortie.
-
-## Setup initial
-
-`sudo` n'est pas installé sur les managed nodes.
-
-On va essayer de tout config en utilisant un vault pour le password root.
-
-```
-$ ansible-vault create creds.yml
-```
-
-stocke dedans :
-
-```
-root_password: ******
-```
-
-Playbook `playbook-initial-setup.yml`.
-
-Le jouer :
-
-```
-ansible-playbook -i inventory.ini playbook-initial-setup.yml --ask-vault-pass -u debian -k
-```
-
-`-k` pour demander password de l'utilisateur régulier `debian`
-`--ask-vault-pass` pour demander le mot de passe du vault
-
-### revert cette étape
-
-* `apt uninstall sudo`
-
-## Ajouter `debian` aux sudoers
-
-```
-ansible-playbook -i inventory.ini playbook-add-debian-sudoers.yml --ask-vault-pass -u debian -k
-```
-
-
-> **→ c'est pas tellement simple**... mais en même temps sans `sudo` on fait ce qu'on peut.
-
-Peut-être qu'un `-K` pour juste demander le mot de passe root sans le mettre dans un vault...
-
-## Lundi 19/02 aprem
-
-### prep
-
-- divise inventory en 2 parties (debian et alpine)
-
-### alpine
-
-#### 1er essai
-
-```
-$ ansible -i ./inventory.ini alpine -m ping -u alpine -k
-SSH password: 
-[WARNING]: No python interpreters found for host 192.168.1.48 (tried ['python3.11', 'python3.10', 'python3.9', 'python3.8', 'python3.7',
-'python3.6', 'python3.5', '/usr/bin/python3', '/usr/libexec/platform-python', 'python2.7', '/usr/bin/python', 'python'])
-192.168.1.48 | FAILED! => {
-    "ansible_facts": {
-        "discovered_interpreter_python": "/usr/bin/python"
-    },
-    "changed": false,
-    "module_stderr": "Shared connection to 192.168.1.48 closed.\r\n",
-    "module_stdout": "/bin/sh: /usr/bin/python: not found\r\n",
-    "msg": "The module failed to execute correctly, you probably need to set the interpreter.\nSee stdout/stderr for the exact error",
-    "rc": 127
-}
-[WARNING]: No python interpreters found for host 192.168.1.72 (tried ['python3.11', 'python3.10', 'python3.9', 'python3.8', 'python3.7',
-'python3.6', 'python3.5', '/usr/bin/python3', '/usr/libexec/platform-python', 'python2.7', '/usr/bin/python', 'python'])
-192.168.1.72 | FAILED! => {
-    "ansible_facts": {
-        "discovered_interpreter_python": "/usr/bin/python"
-    },
-    "changed": false,
-    "module_stderr": "Shared connection to 192.168.1.72 closed.\r\n",
-    "module_stdout": "/bin/sh: /usr/bin/python: not found\r\n",
-    "msg": "The module failed to execute correctly, you probably need to set the interpreter.\nSee stdout/stderr for the exact error",
-    "rc": 127
-}
-```
-
-#### faire installer python3
-
-Attention
-
-- cibler hosts `alpine`
-
-```yaml
-- hosts: alpine
-  gather_facts: no
-  tasks:
-    - name: Install Python3
-      raw: apk update && apk add python3
-```
-
-exec va demander
-
-- password ssh
-- password become
-
-```
-ansible-playbook -i inventory.ini playbook-install-python-alpine.yml -u alpine -bkK
-```
-
-#### 2nde tentative ping
-
-```
-$ ansible -i ./inventory.ini alpine -m ping -u alpine -k
-SSH password: 
-[WARNING]: Platform linux on host 192.168.1.72 is using the discovered Python interpreter at /usr/bin/python3.11, but future installation
-of another Python interpreter could change the meaning of that path. See https://docs.ansible.com/ansible-
-core/2.15/reference_appendices/interpreter_discovery.html for more information.
-192.168.1.72 | SUCCESS => {
-    "ansible_facts": {
-        "discovered_interpreter_python": "/usr/bin/python3.11"
-    },
-    "changed": false,
-    "ping": "pong"
-}
-[WARNING]: Platform linux on host 192.168.1.48 is using the discovered Python interpreter at /usr/bin/python3.11, but future installation
-of another Python interpreter could change the meaning of that path. See https://docs.ansible.com/ansible-
-core/2.15/reference_appendices/interpreter_discovery.html for more information.
-192.168.1.48 | SUCCESS => {
-    "ansible_facts": {
-        "discovered_interpreter_python": "/usr/bin/python3.11"
-    },
-    "changed": false,
-    "ping": "pong"
-}
-```
-
-## Fedora
-
-- DL Fedora Server 39 + checksum depuis <https://fedoraproject.org/server/download>
-    
-    - wget https://download.fedoraproject.org/pub/fedora/linux/releases/39/Server/x86_64/images/Fedora-Server-KVM-39-1.5.x86_64.qcow2
-    - wget https://download.fedoraproject.org/pub/fedora/linux/releases/39/Server/x86_64/images/Fedora-Server-39-1.5-x86_64-CHECKSUM
-- Vérif checksum
-
-    - curl -O https://fedoraproject.org/fedora.gpg
-    - gpgv --keyring ./fedora.gpg Fedora-Server-39-1.5-x86_64-CHECKSUM
-    - sha256sum -c Fedora-Server-39-1.5-x86_64-CHECKSUM
-- Crée VM **sans media** et avec un disque vide 8 Go
-- dans le term en étant sous `/var/lib/vz/template/qcow` : `qm importdisk 131 Fedora-Server-KVM-39-1.5.x86_64.qcow2 local-lvm` (`local` en dernier ne marche pas)
-
-**GROSSE bidouille pour faire marcher le HDD**
-
-```
-   60  qm importdisk
-   61  cd qcow/
-   62  qm importdisk 131 Fedora-Server-KVM-39-1.5.x86_64.qcow2 
-   63  qm importdisk 131 Fedora-Server-KVM-39-1.5.x86_64.qcow2 local
-   64  qm importdisk 131 Fedora-Server-KVM-39-1.5.x86_64.qcow2 local-lvm
-   65  history
-   66  pwd
-   67  qm config 131
-   # --------- Détacher le précédent ide0 ---------
-   68  qm set 131 -ide0 none
-   69  lvremove /dev/local-lvm/vm-131-disk-0
-   70  lvremove /dev/local/vm-131-disk-0
-   71  lvmdump
-   72  cd
-   73  tar tvzf lvmdump-pve-20240219163630.tgz 
-   # --------- Attacher disque importé via qm importdisk sur ide0 et le set en disk boot ---------
-   74  qm set 131 -ide0 local-lvm:vm-131-disk-1
-   75  qm set 131 -boot order=ide0
-   76  history
-```
-
-### post-install
-
-```
-hostnamectl hostname fedora-131
-```
-
-## PLAYBOOKS
-
-Limiter le run du playbook à tel host/groupe : <https://docs.ansible.com/ansible/latest/inventory_guide/intro_patterns.html#patterns-and-ansible-playbook-flags>
-

+ 0 - 6
ansible-initial-debian-setup/ansible.cfg

@@ -1,6 +0,0 @@
-# ansible configuration file
-[defaults]
-host_key_checking = False
-become = True
-become_method = sudo
-become_user = root

+ 0 - 12
ansible-initial-debian-setup/inventory.ini

@@ -1,12 +0,0 @@
-; inventory.ini - ansible inventory file
-[debian]
-debian-111 ansible_host=192.168.1.18 ansible_user=debian ansible_become=true ansible_become_method=sudo ansible_become_user=root ansible_python_interpreter=/usr/bin/python3 
-debian-112 ansible_host=192.168.1.85 ansible_user=debian ansible_become=true ansible_become_method=sudo ansible_become_user=root ansible_python_interpreter=/usr/bin/python3 
-debian-113 ansible_host=192.168.1.109 ansible_user=debian ansible_become=true ansible_become_method=sudo ansible_become_user=root ansible_python_interpreter=/usr/bin/python3 
-
-[alpine]
-alpine-121 ansible_host=192.168.1.72 ansible_user=alpine
-alpine-122 ansible_host=192.168.1.48 ansible_user=alpine
-
-; [fedora]
-; fedora-131 192.168.1.x

+ 0 - 15
ansible-initial-debian-setup/playbook-add-debian-sudoers.yml

@@ -1,15 +0,0 @@
-- hosts: all
-  gather_facts: no  # Désactive la collecte d'informations car cela nécessite Python
-  vars_files:
-    - root-creds.yml
-  tasks:
-    - name: Ajouter l'utilisateur 'debian' au groupe 'sudo'
-      become: yes
-      become_method: su
-      become_user: root
-      user:
-        name: debian
-        groups: sudo
-        append: yes
-      vars:
-        ansible_become_password: "{{ root_password }}"

+ 0 - 31
ansible-initial-debian-setup/playbook-create-sudoers.yml

@@ -1,31 +0,0 @@
----
-- name: Create ansible user with sudo privileges and copy ssh key
-  hosts: all
-  become: true
-  vars:
-    sudoers_file: /etc/sudoers.d/ansible
-    ssh_key_file: /home/ansible/.ssh/authorized_keys
-  tasks:
-    - name: Vérifie existence fichier sudoers
-      stat:
-        path: "{{ sudoers_file }}"
-        mode: '0440'
-      register: stat_sudoers
-      
-    - name: Créer fichier sudoers
-      copy:
-        content: "{{ lookup('template', 'sudoers.j2') }}"
-        dest: "{{ sudoers_file }}"
-        mode: '0440'
-      when: not stat_sudoers.stat.exists
-
-    - name: Create ansible user
-      user:
-        name: ansible
-        createhome: yes
-
-    - name: Copy ssh key to authorized_keys file
-      ansible.posix.authorized_key:
-        user: ansible
-        state: present
-        key: "{{ lookup('file', '~/.ssh/id_ed25519.pub') }}"

+ 0 - 13
ansible-initial-debian-setup/playbook-initial-setup-revert.yml

@@ -1,13 +0,0 @@
----
-- hosts: all
-  gather_facts: no  # Désactive la collecte d'informations car cela nécessite Python
-  vars_files:
-    - root-creds.yml
-  tasks:
-  - name: Uninstall sudo on Debian VMs
-    raw: apt-get remove -y sudo
-    become: yes
-    become_method: su
-    become_user: root
-    vars:
-      ansible_become_password: "{{ root_password }}"

+ 0 - 13
ansible-initial-debian-setup/playbook-initial-setup.yml

@@ -1,13 +0,0 @@
----
-- hosts: all
-  gather_facts: no  # Désactive la collecte d'informations car cela nécessite Python
-  vars_files:
-    - root-creds.yml
-  tasks:
-  - name: Install sudo on Debian VMs
-    raw: apt-get update && apt-get install -y sudo
-    become: yes
-    become_method: su
-    become_user: root
-    vars:
-      ansible_become_password: "{{ root_password }}"

+ 0 - 6
ansible-initial-debian-setup/playbook-install-python-alpine.yml

@@ -1,6 +0,0 @@
-- hosts: alpine
-  gather_facts: no
-  tasks:
-    - name: Install Python3
-      raw: apk update && apk add python3
-

+ 0 - 21
ansible-initial-debian-setup/playbook-install-vim.yml

@@ -1,21 +0,0 @@
----
-- hosts: all
-  gather_facts: no
-  become: true
-  # obligé d'ajouter ce bloc --- DEBUT
-  become_method: su
-  become_user: root
-  vars_files:
-    - root-creds.yml
-  # obligé d'ajouter ce bloc --- FIN
-  vars:
-    package_1: vim
-    package_2: git
-    package_3: etckeeper
-  tasks:
-    - name: "Install Package {{ package_1 }}"
-      apt: name={{ package_1 }} state=latest
-    - name: "Install Package {{ package_2 }}"
-      apt: name={{ package_2 }} state=latest
-    - name: "Install Package {{ package_3 }}"
-      apt: name={{ package_3 }} state=latest

+ 0 - 7
ansible-initial-debian-setup/playbook-whoami.yml

@@ -1,7 +0,0 @@
-- hosts: all
-  become: yes
-  tasks:
-    - name: Who am I?
-      command: whoami
-      register: whoami
-    - debug: var=whoami.stdout

+ 0 - 6
ansible-initial-debian-setup/root-creds.yml

@@ -1,6 +0,0 @@
-$ANSIBLE_VAULT;1.1;AES256
-31643535623531346537366431316239343161393636633061653335313866396430623537336635
-6133386165313337626565346132333534643266326533350a396333653031383338333862386638
-62353333623935333064636431376364376339393639306166323865353538656162303239353636
-6133663031633063340a363730366165343131333037306339356233363134636562373134626163
-37323131343966633131316138343862353734326531323637373266303332616439

+ 0 - 82
lemp--legacy/README-todo.md

@@ -1,82 +0,0 @@
-# Install WP sur Alpine, Debian
-
-## Alpine
-
-### Erreurs rencontrées
-
-Run playbook:
-
-```
-ansible-playbook -i inventory/hosts playbooks/install_php_mysql_alpine.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
-
-## Debian
-
-```
-ansible-playbook -i ../ansible-initial-debian-setup/inventory.ini playbooks/install_php_mysql_debian.yml -K --limit debian-111
-```
-
-Changements par rapport à Alpine
-
-- **ATTENTION** Nginx doit être installé **avant** d'unzip WordPress vers `/var/www` (BUG dans mon playbook Alpine).
-- `pkgconfig` et `mariadb-dev` n'existent pas sous Debian.
-- `php8.2-json` et `php8.2-openssl` non plus
-- `mariadb` non plus => `mariadb-server` et `mariadb-client`
-- install de `mysqlclient` se fait via apt (`python3-mysqldb`)
-- du coup plus besoin d'installer `gcc`, `python3-dev`, `python3-pip`
-- **todo**:
-    - [ ] variables dans vault (a minima password bdd et password wp)
-    - [ ] url du site aussi en variable
-    - [ ] installer `php8.2-gd` pour WP
-    - [ ] **gestion des droits** car `/var/www/wordpress` est créé avec nobody:nobody
- 
-**Passer un fichier de variables** à l'exécution - extrait de `ansible-playbook --help`
-
-```
-  -e EXTRA_VARS, --extra-vars EXTRA_VARS
-                        set additional variables as key=value or YAML/JSON, if filename prepend with @. This argument may be specified multiple times.
-```
-
-### Rendre plus générique
-
-Mis en commentaire le bloc vars
-
-```yaml
-  # vars:
-  #   db_username: wordpress
-  #   db_password: wordpress
-  #   db_name: wordpress
-  #   site_url: debian-111
-```
-
-**Installer tout**
-
-```
-ansible-playbook -i ../ansible-initial-debian-setup/inventory.ini playbooks/install_php_mysql_debian.yml -bkK --limit debian-112 -e @vars-debian-112.yml
-ansible-playbook -i ../ansible-initial-debian-setup/inventory.ini playbooks/install_php_mysql_debian.yml -bkK --limit debian-113 -e @vars-debian-113.yml
-```
-
-**Désinstaller tout**
-
-```
-ansible-playbook -i ../ansible-initial-debian-setup/inventory.ini playbooks/uninstall_php_mysql_debian.yml -bkK --limit debian-112 -e @vars-debian-112.yml
-```

+ 0 - 82
lemp--legacy/ansible-tuto-chatgpt.md

@@ -1,82 +0,0 @@
-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!

+ 0 - 2
lemp--legacy/hosts

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

+ 0 - 223
lemp--legacy/install_php_mysql_alpine.yml

@@ -1,223 +0,0 @@
----
-- name: Install PHP and MySQL on Alpine-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 apk 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

+ 0 - 2
lemp-wordpress-with-roles/README.md

@@ -58,7 +58,5 @@ sudo rm /usr/local/bin/wp
 
 ## Améliorations futures
 
-- [x] EN PARTIE FAIT &rarr; le script de désinstallation manuelle marche bien (mon but était de pouvoir retester le run du playbook from scratch). ~~idempotence install/désinstall pas vraiment à la hauteur~~
-- [x] FAIT ~~droits sur répertoire `/var/www/wordpress` à corriger (n'empêche pas l'installation mais peut poser problème pour installer des plugins WP)~~
 - [ ] le mdp admin de WP est hardcodé pour l'instant
 - [ ] mettre les mdp WordPress et BDD dans un vault

+ 168 - 0
lemp-wordpress-with-roles/roles.md

@@ -0,0 +1,168 @@
+# Les rôles Ansible
+
+Les [rôles Ansible](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse_roles.html) permettent d'organiser des tâches, handlers, fichiers, templates, variables, etc. selon une hiérarchie de fichier bien définie.
+
+L'organisation de ces contenus en rôles favorise leur réutilisation et leur partage avec d'autres utilisateurs.
+
+Plaçons-nous par exemple dans la perspective d'utiliser des playbooks pour déployer des applications web développées en PHP.
+
+On pourrait être tenté d'écrire des playbooks décrivant toute la procédure d'installation :
+
+- de la "stack" logicielle : LAMP (Linux, Apache, MySQL, PHP) ou LEMP (Nginx remplaçant Apache), avec de possibles variantes (utilisation de MariaDB au lieu de MySQL).
+- de l'application elle-même : dans le cas de PHP, on peut citer entre autres WordPress (plateforme de création de sites), MediaWiki (moteur de wiki utilisé par Wikipédia), PostfixAdmin (interface web de gestion de Postfix), phpMyAdmin.
+
+Écrire la procédure entière au sein d'un playbook pour chaque application donnerait lieu à beaucoup de répétition.
+
+En effet, seule l'application installée, et quelques paramètres de configuration du serveur web, changeraient d'un playbook à l'autre.
+
+Les includes et imports permettent de séparer du contenu et de le réutiliser, mais les rôles imposent une structure cohérente et favorisent l'encapsulation d'une fonctionnalité spécifique par rôle.
+
+En bref, les avantages de l'utlisation des rôles sont :
+
+- La réutilisabilité et la modularité : chaque rôle peut encapsuler toutes les tâches, les fichiers, les templates, et les handlers nécessaires pour une fonction spécifique (comme configurer un serveur web Nginx ou déployer une application WordPress).
+- L'organisation et la maintenance : les rôles suivent une structure de répertoire standardisée, ce qui rend le code Ansible plus organisé et plus facile à appréhender.
+- Le partage et la collaboration : les rôles peuvent être facilement partagés entre différents projets via des plateformes comme Ansible Galaxy.
+- La gestion des dépendances et des variables : les rôles permettent de gérer facilement les dépendances entre les rôles ainsi que les variables par défaut spécifiques à chaque rôle, ce qui offre une grande flexibilité pour la personnalisation et la configuration.
+
+## Exemple
+
+> L'exemple complet est à retrouver sur [ce dépôt](https://git.hubbros.fr/bh/ansible-lemp-wordpress).
+
+Si on souhaite déployer WordPress sur une stack LEMP avec Ansible, on peut organiser un playbook avec cette hiérarchie de répertoires et fichiers :
+
+```
+playbook-directory/
+│
+├── roles/
+│   ├── nginx/
+│   │   ├── tasks/
+│   │   │   └── main.yml  # Tâches pour installer et configurer Nginx
+│   │   ├── templates/
+│   │   │   └── nginx-wordpress.conf.j2  # Template Nginx pour WordPress
+│   │   └── handlers/
+│   │       └── main.yml  # Handlers pour redémarrer Nginx
+│   ├── php/
+│   │   ├── tasks/
+│   │   │   └── main.yml  # Tâches pour installer PHP et ses extensions
+│   │   ├── handlers/
+│   │   │   └── main.yml  # Handlers pour redémarrer PHP-FPM
+│   │   └── templates/
+│   │       └── php.ini.j2  # Template pour la configuration PHP
+│   ├── mysql/
+│   │   └── tasks/
+│   │       └── main.yml  # Tâches pour installer MySQL/MariaDB et configurer la base de données
+│   ├── wordpress/
+│   │   ├── tasks/
+│   │   │   └── main.yml  # Tâches pour installer WordPress et WP-CLI, configurer wp-config.php
+│   │   └── templates/
+│   │   │   └── wp-config-sample.php.j2  # Template pour wp-config.php
+│   └── common/
+│       └── tasks/
+│           └── main.yml  # Tâches communes comme la mise à jour des paquets
+│
+├── hosts.ini  # Fichier d'inventaire
+└── site.yml  # Playbook principal
+```
+
+### Contenu de `site.yml`
+
+C'est le playbook qui va permettre de déployer la stack et l'application, en utilisant des rôles.
+
+```yaml
+---
+- name: Déployer la stack LEMP + WordPress sur Debian 12
+  hosts: all
+  become: yes
+
+  roles:
+    - common
+    - nginx
+    - php
+    - mysql
+    - wordpress
+
+```
+
+Les tâches associées aux rôles référencés ici, et stockées sous `roles/<nom_role>/tasks/main.yml`, vont être exécutées dans l'ordre.
+
+### Contenu de `roles/common/tasks/main.yml`
+
+Ce fichier contient des tâches génériques, telles que la mise à jour du cache apt, et l'installation de paquets qui seront utiles pour la suite, sans être spécifiquement liés à un certain rôle.
+
+```yaml
+---
+- name: Mettre à jour le cache apt
+  ansible.builtin.apt:
+    update_cache: yes
+
+# Installer curl - pour télécharger WordPress et wp-cli
+- name: Installer curl
+  ansible.builtin.apt:
+    name: curl
+    state: present
+```
+
+### Contenu de `roles/nginx/tasks/main.yml`
+
+Dans l'ordre, on va ici :
+
+- installer Nginx,
+- le démarrer,
+- créer une configuration Nginx pour PHP - et plus spécifiquement WordPress, bien qu'elle soit utilisable avec des variations mineures pour d'autres applications PHP ; cette configuration est créé à partir d'un _template_
+- supprimer le lien symbolique de la configuration par défaut, prévue pour servir uniquement des fichiers statiques (HTML, CSS, etc.),
+- créer le lien symbolique permettant d'activer notre configuration,
+- **enfin**, redémarrer Nginx
+
+```yaml
+---
+- name: Installer Nginx
+  ansible.builtin.apt:
+    name: nginx
+    state: present
+
+- name: Démarrer le service Nginx
+  ansible.builtin.service:
+    name: nginx
+    state: started
+    enabled: yes # S'assurer que le service MySQL démarre au boot
+
+- name: Créer la config Nginx pour PHP + WordPress
+  ansible.builtin.template:
+    src: templates/nginx-wordpress.conf.j2
+    dest: /etc/nginx/sites-available/nginx-wordpress.conf
+    owner: root
+    group: root
+    mode: 0644
+
+- name: Supprimer le lien symbolique `default` de sites-enabled
+  ansible.builtin.file:
+    path: /etc/nginx/sites-enabled/default
+    state: absent
+
+- name: Créer un lien symbolique de sites-available/nginx-wordpress.conf vers sites-enabled
+  ansible.builtin.file:
+    src: /etc/nginx/sites-available/nginx-wordpress.conf
+    dest: /etc/nginx/sites-enabled/nginx-wordpress.conf
+    state: link
+  notify: restart nginx 
+
+```
+
+L'action de _redémarrer Nginx_ n'apparaît pas ici directement, mais sous la forme de la dernière ligne `notify: restart nginx`.
+
+Elle fait référence à un handler défini dans un fichier placé également à un endroit standard&hellip;
+
+### Contenu de `roles/nginx/hamdlers/main.yml`
+
+C'est ce fichier qui contient le handler référencé dans le fichier précédent. Voici son contenu :
+
+```yaml
+---
+- name: restart nginx
+  ansible.builtin.service:
+    name: nginx
+    state: restarted
+    enabled: yes # S'assurer que le service Nginx démarre au boot
+
+```
+

+ 1 - 1
lemp-wordpress-with-roles/roles/nginx/handlers/main.yml

@@ -3,4 +3,4 @@
   ansible.builtin.service:
     name: nginx
     state: restarted
-    enabled: yes # S'assurer que le service PHP-FPM démarre au boot
+    enabled: yes # S'assurer que le service Nginx démarre au boot