Skip to main content

Playbooks and Modules

Updated Dec 10, 2020 ·

Overview

Modules perform actions. Playbooks arrange those actions into repeatable YAML workflows.

Use ad hoc commands for quick one-time work, and use playbooks when the task should be repeated, reviewed, or versioned.

Ad Hoc Commands

Run a module directly from the command line.

ansible all -m ping
ansible webservers -m command -a "uptime"
ansible webservers -m yum -a "name=httpd state=present" --become

Useful flags:

FlagPurpose
-iSets the inventory file.
-mSelects the module.
-aPasses module arguments.
-bRuns with privilege escalation.
-uSets the remote user.

Playbook Structure

A playbook contains one or more plays. Each play targets hosts and runs tasks.

---
- name: Check host connectivity
hosts: all
tasks:
- name: Ping hosts
ansible.builtin.ping:

Run the playbook.

ansible-playbook sample-ping.yml

Common Modules

ModulePurpose
pingConfirms Ansible can connect to a host.
commandRuns a command without shell processing.
shellRuns a command through a shell.
copyCopies local files to remote hosts.
templateRenders Jinja2 templates to remote hosts.
serviceStarts, stops, restarts, and enables services.
lineinfileEnsures a line exists or is changed in a file.
yumManages packages on RHEL-based systems.
aptManages packages on Debian-based systems.

Validation

Check syntax before running.

ansible-playbook --syntax-check playbooks/setup-app.yml

Run in check mode when a module supports it.

ansible-playbook playbooks/setup-app.yml --check

Limit a run to specific hosts.

ansible-playbook playbooks/setup-app.yml --limit webservers