Skip to main content

Ad-hoc commands


Chapter objectives

  • Understand ad-hoc commands
  • Use common modules
  • Run quick tasks
  • Diagnose systems

1 - What is an ad-hoc command?

Definition

An ad-hoc command is an Ansible command run directly on the command line, without a playbook.

Syntax

ansible <pattern> -m <module> -a "<arguments>" [options]
ElementDescriptionExample
patternTarget hostsall, webservers, web-01
-mModule to useping, shell, apt
-aModule arguments"name=nginx state=present"

When to use it?


2 - Essential modules

ping - Connectivity test

# Tester tous les hôtes
ansible all -m ping

# Tester un groupe
ansible webservers -m ping

# Résultat
web-01 | SUCCESS => {
"changed": false,
"ping": "pong"
}
info

The ping module does not do an ICMP ping! It verifies that:

  • SSH works
  • Python is available
  • Ansible can run

command - Run a command

# Exécuter une commande simple
ansible all -m command -a "uptime"

# Equivalent (command est le module par défaut)
ansible all -a "uptime"

# Voir l'espace disque
ansible all -a "df -h"

# Vérifier un service
ansible all -a "systemctl status nginx"

shell - Advanced shell commands

# Utiliser des pipes et redirections
ansible all -m shell -a "ps aux | grep nginx"

# Variables d'environnement
ansible all -m shell -a "echo $HOME"

# Redirection
ansible all -m shell -a "cat /var/log/syslog | tail -20"

3 - File management

copy - Copy files

# Copier un fichier
ansible webservers -m copy -a "src=/local/file.txt dest=/remote/file.txt"

# Avec permissions
ansible webservers -m copy -a "src=nginx.conf dest=/etc/nginx/nginx.conf owner=root group=root mode=0644"

# Créer un fichier avec contenu
ansible all -m copy -a "content='Hello World' dest=/tmp/hello.txt"

file - Manage files and directories

# Créer un répertoire
ansible all -m file -a "path=/opt/myapp state=directory mode=0755"

# Créer un lien symbolique
ansible all -m file -a "src=/opt/myapp/current dest=/opt/myapp/latest state=link"

# Supprimer un fichier
ansible all -m file -a "path=/tmp/old_file.txt state=absent"

# Changer les permissions
ansible all -m file -a "path=/var/log/app.log owner=app group=app mode=0640"

fetch - Retrieve files

# Récupérer un fichier depuis les serveurs
ansible webservers -m fetch -a "src=/var/log/nginx/error.log dest=./logs/ flat=yes"

# Récupérer avec structure
ansible all -m fetch -a "src=/etc/hostname dest=./backup/"

4 - Package management

apt (Debian/Ubuntu)

# Mettre à jour le cache
ansible webservers -m apt -a "update_cache=yes" --become

# Installer un package
ansible webservers -m apt -a "name=nginx state=present" --become

# Installer plusieurs packages
ansible webservers -m apt -a "name=nginx,vim,htop state=present" --become

# Supprimer un package
ansible webservers -m apt -a "name=apache2 state=absent" --become

# Mettre à jour tous les packages
ansible webservers -m apt -a "upgrade=dist" --become

yum/dnf (RHEL/CentOS)

# Installer
ansible databases -m yum -a "name=postgresql15-server state=present" --become

# Avec dnf
ansible databases -m dnf -a "name=postgresql15-server state=present" --become

package (generic)

# Fonctionne sur tous les systèmes
ansible all -m package -a "name=git state=present" --become

5 - Service management

service/systemd

# Démarrer un service
ansible webservers -m service -a "name=nginx state=started" --become

# Arrêter un service
ansible webservers -m service -a "name=nginx state=stopped" --become

# Redémarrer
ansible webservers -m service -a "name=nginx state=restarted" --become

# Activer au démarrage
ansible webservers -m service -a "name=nginx enabled=yes" --become

# Recharger la configuration
ansible webservers -m service -a "name=nginx state=reloaded" --become

6 - User management

user - Manage users

# Créer un utilisateur
ansible all -m user -a "name=deploy state=present" --become

# Avec options
ansible all -m user -a "name=deploy shell=/bin/bash groups=sudo append=yes" --become

# Avec clé SSH
ansible all -m user -a "name=deploy generate_ssh_key=yes ssh_key_bits=4096" --become

# Supprimer un utilisateur
ansible all -m user -a "name=olduser state=absent remove=yes" --become

group - Manage groups

# Créer un groupe
ansible all -m group -a "name=developers state=present" --become

# Supprimer un groupe
ansible all -m group -a "name=oldgroup state=absent" --become

authorized_key - SSH keys

# Ajouter une clé SSH
ansible all -m authorized_key -a "user=deploy key='ssh-rsa AAAA... user@host'" --become

# Depuis un fichier
ansible all -m authorized_key -a "user=deploy key='{{ lookup(\"file\", \"/home/user/.ssh/id_rsa.pub\") }}'" --become

7 - Gathering information

setup - System facts

# Tous les facts
ansible web-01 -m setup

# Filtrer les facts
ansible web-01 -m setup -a "filter=ansible_distribution*"

# Facts réseau
ansible web-01 -m setup -a "filter=ansible_default_ipv4"

# Facts mémoire
ansible web-01 -m setup -a "filter=ansible_memory_mb"

Example output

{
"ansible_distribution": "Ubuntu",
"ansible_distribution_version": "22.04",
"ansible_distribution_release": "jammy",
"ansible_os_family": "Debian"
}

debug - Display information

# Afficher un message
ansible localhost -m debug -a "msg='Hello from Ansible'"

# Afficher une variable
ansible localhost -m debug -a "var=ansible_version"

8 - Important options

Common options

# Devenir root (sudo)
ansible all -m apt -a "name=nginx" --become

# Spécifier l'utilisateur become
ansible all -m command -a "id" --become --become-user=postgres

# Demander le mot de passe sudo
ansible all -m command -a "id" --become --ask-become-pass

# Limiter le parallélisme
ansible all -a "uptime" --forks=1

# Mode check (dry-run)
ansible all -m apt -a "name=nginx state=present" --check

# Mode verbose
ansible all -m ping -v
ansible all -m ping -vvv

# Limiter à certains hôtes
ansible all -m ping --limit web-01

9 - Practical use cases

System diagnostic

# Vérifier l'espace disque
ansible all -a "df -h"

# Vérifier la mémoire
ansible all -a "free -m"

# Vérifier les processus
ansible all -m shell -a "ps aux | head -10"

# Vérifier les ports ouverts
ansible all -m shell -a "ss -tlnp"

# Vérifier l'uptime
ansible all -a "uptime"

Quick maintenance

# Redémarrer un service sur tous les serveurs
ansible webservers -m service -a "name=nginx state=restarted" --become

# Vider un cache
ansible webservers -a "rm -rf /var/cache/nginx/*" --become

# Synchroniser l'heure
ansible all -m command -a "timedatectl set-ntp true" --become

Quick deployment

# Copier une configuration
ansible webservers -m copy -a "src=nginx.conf dest=/etc/nginx/nginx.conf backup=yes" --become

# Recharger le service
ansible webservers -m service -a "name=nginx state=reloaded" --become

# Vérifier que ça fonctionne
ansible webservers -m uri -a "url=http://localhost status_code=200"

10 - Best practices

Security

# ✅ Éviter shell quand possible
ansible all -m command -a "cat /etc/passwd"

# ❌ Éviter (injection possible)
ansible all -m shell -a "cat $USER_INPUT"

Idempotence

# ✅ Idempotent
ansible all -m file -a "path=/tmp/test state=directory"

# ❌ Non idempotent
ansible all -m shell -a "mkdir /tmp/test"

Documentation

# Toujours vérifier la documentation
ansible-doc apt
ansible-doc -l | grep -i user

Summary

Key points
  • Use ad-hoc for one-off tasks
  • Prefer command over shell when possible
  • Don't forget --become for privileged tasks
  • Use --check to test before running

Practical exercises

  1. Test the connectivity of all your hosts
  2. Check the disk space on the webservers group
  3. Install vim on all servers
  4. Create a "deploy" user with an SSH key

← Inventory | Playbooks →