Cheat sheet de Ansible

Referencia de comandos de Ansible con búsqueda: comandos ad-hoc, playbooks, roles, plantillas, handlers, bucles, Vault y Galaxy, con cada parámetro explicado.

Se ejecuta en tu navegador · no se envía nadaNuevo

39 comandos

Setup & info

ansible --versionShow the installed Ansible version, Python version and the path to the active config file.

Useful to confirm which ansible.cfg is actually being loaded, since Ansible searches several locations (ANSIBLE_CONFIG, ./ansible.cfg, ~/.ansible.cfg, /etc/ansible/ansible.cfg) in that order.

ansible-config dumpShow every active configuration setting, including defaults.

Ejemplo

ansible-config dump --only-changed

Opciones

--only-changedShow only the settings you have changed from their default value.
-c <file>Use a specific config file instead of the one Ansible would normally find.
ansible-doc <module>Show documentation for a module, including its parameters and examples.

Ejemplo

ansible-doc ansible.builtin.copy

Opciones

-lList all available modules.
-t moduleLimit to module documentation (the default; also accepts lookup, filter, etc.).
-sShow a short "snippet" form ready to paste into a playbook.
-FShow every plugin name and which file it comes from.

Inventory

ansible-inventory --listShow the full inventory as JSON, with all groups, hosts and variables resolved.

Useful for checking what Ansible actually sees after merging static files, dynamic inventory plugins and group/host variable files.

ansible-inventory --graphShow groups and hosts as a tree, without the variables.

Ejemplo

ansible-inventory --graph --vars

Opciones

--varsAlso show the variables for each host and group.
ansible <pattern> --list-hostsList the hosts that a pattern matches, without running anything against them.

A quick way to check a pattern is correct before you run it for real. "all" matches every host; a group name matches that group; "web*" matches by wildcard.

Ejemplo

ansible web --list-hosts
[group]\nhost ansible_host=<ip>Basic structure of a static INI-style inventory file.

A group header in brackets, then one host per line with optional connection variables. "[all:vars]" sets variables for every host, and "[prod:children]" builds a group out of other groups.

Ejemplo

[web]
web1 ansible_host=192.168.1.21

[all:vars]
ansible_user=ubuntu
ansible_python_interpreter=/usr/bin/python3

[prod:children]
web
db

Ad-hoc commands

ansible all -m ansible.builtin.pingCheck that Ansible can connect to and run Python on every host in the inventory.

This does not test network connectivity (ICMP); it confirms SSH access and a working Python interpreter, which is what every other module needs.

Opciones

-i <file>Use a specific inventory file instead of the default one.
-i 'host,'Use an inline inventory (note the trailing comma for a single host).
ansible <pattern> -m <module> -a "<args>"Run a single module against matching hosts without writing a playbook.

Good for one-off checks and fixes. For anything you will run more than once, write a playbook instead so it is repeatable and version-controlled.

Ejemplo

ansible web -m ansible.builtin.apt -a "name=apache2 state=present" -b -K

Opciones

-m <module>Module to run, for example ansible.builtin.apt, ansible.builtin.copy, ansible.builtin.service.
-a "<args>"Module arguments as a space-separated key=value string.
-bUse become to execute with elevated privileges (like sudo).
-KPrompt for the become (privilege escalation) password.
-u <user>Connect over SSH as this user.
-kPrompt for the SSH password instead of using key-based auth.
ansible all -m ansible.builtin.setupCollect and display system facts (OS, IP addresses, memory, CPU, mounted filesystems) from each host.

Ejemplo

ansible web -m ansible.builtin.setup -a "filter=ansible_distribution*"

Opciones

-a "filter=<pattern>"Only show facts whose name matches this wildcard pattern.
ansible all -m ansible.builtin.reboot -bReboot matching hosts and wait for them to come back online.
Cuidado: This restarts every matched host. Double-check the pattern (especially with "all") before running it, and consider --limit to narrow it down first.

Playbooks

ansible-playbook <playbook>.ymlRun a playbook against the hosts and groups it targets.

Ejemplo

ansible-playbook -i inventory.ini -u deploy -b -K site.yml

Opciones

-i <file>Inventory file to use for the pattern in the playbook.
-u <user>Connect over SSH as this user.
-kAsk for the SSH password.
-f <n>Number of parallel forks (hosts processed at the same time). Default is 5.
-T <seconds>Connection timeout in seconds.
-t <tag>Only run tasks (and plays) tagged with this tag.
--skip-tags <tag>Run everything except tasks tagged with this tag.
-M <path>Load local modules from this path, in addition to the built-in ones.
-bExecute with elevated privileges (uses become, like sudo).
-KPrompt for the become password.
ansible-playbook <playbook>.yml --checkDry run: show what would change without actually making any changes.

Not every module supports check mode equally well; some report "changed" conservatively when they cannot be sure. Combine with --diff to see the actual content differences for file-based tasks.

Opciones

--diffShow a before/after diff for tasks that change file content or templates.
ansible-playbook <playbook>.yml --limit <pattern>Restrict a playbook run to a subset of the hosts it would otherwise target.

The pattern is checked against hosts already selected by the play's own "hosts:" line; it narrows that selection, it does not add hosts outside it.

Ejemplo

ansible-playbook site.yml --limit "web1,web2"
ansible-playbook <playbook>.yml --stepConfirm interactively before each task runs.

Useful while writing or debugging a new playbook, to see exactly where something goes wrong without waiting for the whole run to fail.

ansible-playbook <playbook>.yml --list-tasksList every task the playbook would run, with its tags, without running anything.

Opciones

--list-tagsList the available tags instead of tasks.
--list-hostsList the hosts the playbook would target.
ansible-playbook <playbook>.yml --syntax-checkCheck the playbook YAML for syntax errors without connecting to any host or running anything.

The fastest sanity check before a real run, and safe to use in CI.

ansible-playbook <playbook>.yml -vShow more detail in the output, including the result of each module call.

Repeat the flag for more detail: -vv adds connection information, -vvv adds raw SSH and module arguments, -vvvv enables plugin-level debugging. -vvv is a reasonable starting point for diagnosing a failing task.

Opciones

-vBasic extra output.
-vvvConnection and module argument detail, good for most troubleshooting.
-vvvvMaximum detail, including plugin loading.

Vault

ansible-vault create secrets.ymlCreate a new file, encrypted with AES256, and open it in your editor.

Ansible Vault lets you keep secrets (passwords, API keys, certificates) in the same repository as your playbooks, as ciphertext instead of plain text.

Opciones

--vault-id <label@source>Use a named vault identity, so different files can be encrypted with different passwords.
--ask-vault-passPrompt for the password instead of reading it from a file.
--vault-password-file <file>Read the password from this file (or script, if executable).
ansible-vault encrypt <file>Encrypt an existing plaintext file in place.

Ejemplo

ansible-vault encrypt group_vars/prod/vault.yml
Cuidado: This overwrites the file with its encrypted form. Make sure you have the content committed or backed up before encrypting, in case you need the original plaintext again.
ansible-vault decrypt <file>Decrypt a file in place, turning it back into plain text.
Cuidado: The file becomes plain text on disk. Do not commit it in this state if it still contains real secrets.
ansible-vault view <file>Print the decrypted content to the terminal without writing a plaintext file to disk.

The safer way to just read a secret without risking an accidental plaintext commit.

ansible-vault edit <file>Decrypt, open in your editor, and re-encrypt on save, without leaving a plaintext file behind.

The preferred way to make a small change to an encrypted file; combining separate decrypt/edit/encrypt steps risks leaving plaintext on disk if you forget the last step.

ansible-vault rekey <file>Change the password used to encrypt a file.

Needed when a vault password may have leaked, or when rotating secrets as part of regular hygiene.

ansible-vault encrypt_string '<value>' --name '<var_name>'Encrypt a single value (not a whole file) for pasting directly into a playbook or variables file.

Produces a "!vault |" YAML block you can paste inline, so most of a variables file can stay in plain text while only the sensitive value is encrypted.

Ejemplo

ansible-vault encrypt_string 'S3cretPass!' --name 'db_password'
ansible-playbook <playbook>.yml --ask-vault-passRun a playbook that references vault-encrypted files or variables, prompting for the password.

Opciones

--ask-vault-passPrompt for the vault password interactively.
--vault-password-file <file>Read the vault password from a file or script instead of prompting.

Galaxy

ansible-galaxy collection install <namespace.collection>Download and install a collection of modules, roles and plugins from Ansible Galaxy.

Downloads from the configured Galaxy server (galaxy.ansible.com by default) unless a different server is set in ansible.cfg.

Ejemplo

ansible-galaxy collection install community.general
ansible-galaxy collection install -r requirements.ymlInstall every collection (and optionally role) listed in a requirements.yml file.

The standard way to pin and reproduce the exact set of collections a project depends on, instead of installing them one at a time.

ansible-galaxy collection listList every collection installed, and where each one was installed from.

Useful to check whether a collection came from the project-local collections path or a system-wide one, since Ansible searches several locations in order.

ansible-galaxy role install <namespace.role>Download and install a role from Ansible Galaxy into ~/.ansible/roles by default.

Ejemplo

ansible-galaxy role install geerlingguy.nginx

Opciones

-p <path>Install into a specific path instead of the default roles directory.
ansible-galaxy role listList every role currently installed.

Lists roles installed via ansible-galaxy, not roles that simply exist as plain directories under a project's roles/ folder.

ansible-galaxy init <role_name>Scaffold a new role with the standard directory structure (tasks, handlers, templates, defaults, meta).

Creates the folders Ansible expects for a role, with placeholder files, so you do not have to remember the exact layout by hand.

Playbook logic & templates

- name: <task> <module>: ... when: <condition>Run a task only when a condition is true, based on a variable, fact, or a previous task's registered result.

The condition is plain Jinja2, without the {{ }} delimiters needed elsewhere. Multiple when conditions in a list are combined with AND.

Ejemplo

- name: Install Apache on Debian family
  ansible.builtin.apt:
    name: apache2
    state: present
  when: ansible_facts['os_family'] == "Debian"
- name: <task> <module>: "{{ item }}" loop: <list>Run a task once for each item in a list.

loop is the modern replacement for the older with_<lookup> syntax (with_items, with_dict, and so on), which still works but is no longer the recommended form.

Ejemplo

- name: Create directories
  ansible.builtin.file:
    path: "/data/{{ item }}"
    state: directory
  loop:
    - logs
    - uploads
    - cache

Opciones

loop_control.labelControl what is shown in the task output per iteration, useful when looping over large/complex dictionaries.
loop_control.pauseWait a number of seconds between iterations.
- name: <task> <module>: ... register: <var>Capture the result of a task (success/failure, output, return values) into a variable for use in later tasks.

Ejemplo

- name: Check if file exists
  ansible.builtin.stat:
    path: /etc/myapp/config.yml
  register: config_file

- name: Create default config
  ansible.builtin.copy:
    src: default-config.yml
    dest: /etc/myapp/config.yml
  when: not config_file.stat.exists
tasks: - name: <task> <module>: ... notify: <handler-name> handlers: - name: <handler-name> <module>: ...A handler is a task that only runs when notified by another task, typically used to restart or reload a service after a config change.

By default, handlers run once at the end of the play (or at explicit flush points), even if notified by several tasks, so a service is reloaded once no matter how many config files changed.

Ejemplo

tasks:
  - name: Deploy nginx config
    ansible.builtin.template:
      src: nginx.conf.j2
      dest: /etc/nginx/nginx.conf
    notify: Reload nginx
handlers:
  - name: Reload nginx
    ansible.builtin.service:
      name: nginx
      state: reloaded
- name: <task> ansible.builtin.template: src: <file>.j2 dest: <path>Render a Jinja2 template file, substituting variables and facts, and copy the result to the target host.

Unlike ansible.builtin.copy, template always processes the file through the Jinja2 engine first; any {{ }} or {% %} in the source file is evaluated, not copied literally.

Ejemplo

# nginx.conf.j2
server {
  listen {{ http_port }};
  server_name {{ inventory_hostname }};
}

Opciones

validate "<command> %s"Run a validation command against the rendered file before it replaces the real destination, for example "nginx -t -c %s".
backup: trueKeep a timestamped backup of the previous file before overwriting it.
roles/<role_name>/{tasks,handlers,templates,files,vars,defaults,meta}/The standard directory layout Ansible expects for a role: each subfolder has a specific purpose and only needs a main.yml if that feature is used.

tasks/main.yml is the entry point; handlers/main.yml holds handlers; templates/ and files/ hold the respective source files (found automatically by template/copy without a full path, from within the role); defaults/main.yml holds overridable default variables (lowest precedence); vars/main.yml holds role variables (higher precedence, not meant to be overridden by callers).

Opciones

defaults/main.ymlDefault values, easily overridden by the playbook or inventory.
vars/main.ymlRole-internal variables, higher precedence, not intended for external overriding.
meta/main.ymlRole metadata and dependencies on other roles.
- hosts: <group> roles: - <role_name> - role: <role_name> vars: <key>: <value>Apply a role to a play, optionally overriding its default variables.

ansible.builtin.include_role (used as a task, not at the play level) applies a role conditionally or partway through a task list instead of always at play start, which the simpler "roles:" list does not support.

Las descripciones de esta referencia están por ahora en inglés.

Explicación

Busca o filtra por grupo y copia un comando con un clic. Abre un comando para ver qué hace, un ejemplo y cada parámetro que acepta, con avisos donde afecta a cada host coincidente.

🔒 Tu entrada se queda en tu navegador y no se envía a ningún sitio.

Preguntas frecuentes

¿Qué hace --check en ansible-playbook?

Ejecuta una simulación: Ansible informa de lo que cambiaría sin cambiar nada realmente. Combínalo con --diff para ver las diferencias de contenido en tareas basadas en archivos.

¿Cuál es la diferencia entre un handler y una tarea normal?

Un handler solo se ejecuta cuando otra tarea lo notifica explícitamente (normalmente para reiniciar o recargar un servicio tras un cambio de configuración), y por defecto se ejecuta una sola vez al final de la play aunque varias tareas lo notifiquen.

Qué hacer después

Más en esta sección

  • Cheat sheet de AWS CLIReferencia de AWS CLI con búsqueda: configuración, S3, EC2, VPC/Route 53, CloudWatch, Lambda, ECR/ECS, IAM y CloudFormation, con cada opción explicada.
  • Cheat sheet de Azure CLIReferencia de comandos de Azure CLI con búsqueda: inicio de sesión, grupos de recursos, VMs, almacenamiento, web apps y AKS, con cada parámetro explicado.

También útil

¿Has encontrado un problema o tienes una sugerencia? Cuéntanoslo