Ansible est un outil d’automatisation open source pour la gestion de configuration, le déploiement d’applications et l’orchestration sans agent.
⚙️ Installation
📌 Plateforme | 🧠 Commande |
---|
🐧 Ubuntu/Debian | sudo apt update && sudo apt install ansible |
🎩 CentOS/RHEL | sudo yum install ansible |
🐍 Python pip | pip3 install ansible |
🍺 macOS (Homebrew) | brew install ansible |
📁 Structure projet recommandée
ansible-project/
├── inventory/ # Inventaires
│ ├── production/
│ │ ├── hosts.ini
│ │ └── group_vars/
│ └── staging/
│ └── hosts.ini
├── roles/ # Rôles réutilisables
│ ├── common/
│ ├── nginx/
│ └── mysql/
├── playbooks/ # Playbooks principaux
│ ├── site.yml
│ └── webservers.yml
├── group_vars/ # Variables par groupe
├── host_vars/ # Variables par hôte
└── ansible.cfg # Configuration
Fichier ansible.cfg
[defaults]
inventory = inventory/ # Dossier inventaire par défaut
remote_user = ansible # Utilisateur SSH par défaut
host_key_checking = False # Pas de vérification clé SSH (dev)
retry_files_enabled = False # Pas de fichiers .retry
gathering = smart # Collecte intelligente des facts
fact_caching = memory # Cache facts en mémoire
[ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=60s # Connexions SSH persistantes
pipelining = True # Optimisation SSH
📋 Gestion inventaire
📌 Action | 🧠 Commande |
---|
📝 Créer inventaire | echo "[servers]" > inventory/hosts.ini |
🏓 Test ping global | ansible all -m ping |
🎯 Test ping groupe | ansible webservers -m ping |
⏰ Commande ad-hoc | ansible all -a "uptime" |
📊 Infos système | ansible all -m setup |
🎯 Autre inventaire | ansible all -i staging/hosts.ini -m ping |
Exemple fichier inventaire
[webservers]
web1 ansible_host=192.168.1.50 ansible_user=admin
web2 ansible_host=192.168.1.51 ansible_user=admin
[databases]
db1 ansible_host=192.168.1.20 ansible_user=root
[all:vars]
ansible_python_interpreter=/usr/bin/python3
ansible_ssh_private_key_file=~/.ssh/id_rsa
Variables d’inventaire utiles
# Connexion SSH
ansible_host=192.168.1.50 # IP du serveur
ansible_user=admin # Utilisateur SSH
ansible_port=2222 # Port SSH (défaut: 22)
ansible_ssh_private_key_file=~/.ssh/key # Clé privée
# Python
ansible_python_interpreter=/usr/bin/python3
# Sudo
ansible_become=yes # Utiliser sudo
ansible_become_user=root # Utilisateur sudo
🚀 Exécution playbooks
📌 Action | 🧠 Commande |
---|
▶️ Exécuter playbook | ansible-playbook playbook.yml |
🧪 Mode test (dry-run) | ansible-playbook playbook.yml --check |
🔍 Mode verbeux | ansible-playbook playbook.yml -vvv |
🎯 Limite aux hosts | ansible-playbook playbook.yml --limit webservers |
📋 Lister tâches | ansible-playbook playbook.yml --list-tasks |
🏠 Host direct | ansible-playbook -i "192.168.1.50," playbook.yml |
Structure playbook basique
---
- name: Configuration serveurs web
hosts: webservers
become: yes
vars:
nginx_port: 80
tasks:
- name: Installer nginx
apt:
name: nginx
state: present
update_cache: yes
- name: Démarrer nginx
service:
name: nginx
state: started
enabled: yes
handlers:
- name: restart nginx
service:
name: nginx
state: restarted
🎭 Gestion des rôles
Ansible Galaxy est un hub communautaire de rôles partagés (optionnel)
📌 Action | 🧠 Commande |
---|
🆕 Créer structure rôle | ansible-galaxy init nginx |
🛠️ Créer manuellement | mkdir -p roles/nginx/{tasks,handlers,templates,files,vars,defaults} |
📦 Installer rôle communautaire | ansible-galaxy install geerlingguy.nginx |
📋 Lister rôles installés | ansible-galaxy list |
🗑️ Supprimer un rôle | ansible-galaxy remove geerlingguy.nginx |
🔍 Chercher des rôles | ansible-galaxy search nginx |
Structure d’un rôle
roles/nginx/
├── tasks/main.yml # Tâches principales
├── handlers/main.yml # Actions déclenchées (restart services)
├── templates/ # Fichiers Jinja2 (.j2)
├── files/ # Fichiers statiques à copier
├── vars/main.yml # Variables du rôle
├── defaults/main.yml # Variables par défaut
└── meta/main.yml # Métadonnées (dépendances, etc.)
Utiliser des rôles dans un playbook
---
- name: Déploiement serveurs web
hosts: webservers
become: yes
roles:
- common # Configuration de base
- nginx # Installation et config Nginx
- firewall # Configuration firewall
# Ou avec paramètres
- name: Config avec variables
hosts: webservers
roles:
- role: nginx
vars:
nginx_port: 8080
nginx_user: www-data
🔧 Modules essentiels
Gestion packages
# APT (Ubuntu/Debian)
- name: Installer nginx
apt:
name: nginx
state: present
update_cache: yes
# YUM/DNF (CentOS/RHEL/Fedora)
- name: Installer httpd
yum:
name: httpd
state: present
# Package universel
- name: Installer git
package:
name: git
state: present
Gestion fichiers
# Copier fichier
- name: Copier configuration
copy:
src: files/nginx.conf
dest: /etc/nginx/nginx.conf
owner: root
group: root
mode: '0644'
backup: yes
# Template Jinja2
- name: Générer config dynamique
template:
src: templates/config.j2
dest: /etc/app/config.conf
# Créer dossier
- name: Créer répertoire
file:
path: /opt/myapp
state: directory
mode: '0755'
Gestion services
# Contrôler service
- name: Démarrer et activer nginx
service:
name: nginx
state: started
enabled: yes
# Service systemd
- name: Recharger systemd
systemd:
name: myapp
state: reloaded
daemon_reload: yes
🔐 Ansible Vault
📌 Action | 🧠 Commande |
---|
🔒 Créer fichier chiffré | ansible-vault create secrets.yml |
✏️ Éditer fichier | ansible-vault edit secrets.yml |
🔓 Voir contenu | ansible-vault view secrets.yml |
🔑 Changer mot de passe | ansible-vault rekey secrets.yml |
🔐 Chiffrer fichier existant | ansible-vault encrypt vars.yml |
🔓 Déchiffrer fichier | ansible-vault decrypt vars.yml |
▶️ Exécuter avec vault | ansible-playbook site.yml --ask-vault-pass |
💡 Bonnes pratiques
📌 Pratique | 💬 Description |
---|
🔒 Idempotence | Les tâches produisent toujours le même résultat |
📝 Nommage | Nommer clairement toutes les tâches |
🧪 Tests | Utiliser --check avant déploiement |
📦 Rôles | Organiser en rôles réutilisables |
🔐 Secrets | Chiffrer avec ansible-vault |
🏷️ Tags | Utiliser des tags pour exécutions partielles |