A quick reference for Ansible โ the agentless automation platform. Bookmark this page.
Ad-Hoc Commands
# Ping all hosts
ansible all -m ping
# Run a command
ansible webservers -m command -a "uptime"
ansible webservers -m shell -a "df -h | grep /dev/sda"
# Copy file
ansible all -m copy -a "src=./app.conf dest=/etc/app.conf"
# Install package
ansible all -m dnf -a "name=nginx state=present" -b
# Manage service
ansible all -m service -a "name=nginx state=started enabled=true" -b
# Gather facts
ansible webservers -m setup
ansible webservers -m setup -a "filter=ansible_os_family"Playbook Structure
---
- name: Configure web servers
hosts: webservers
become: true
vars:
http_port: 80
app_version: "2.1.0"
tasks:
- name: Install packages
ansible.builtin.dnf:
name:
- nginx
- python3
state: present
- name: Deploy configuration
ansible.builtin.template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: Restart nginx
- name: Ensure service is running
ansible.builtin.service:
name: nginx
state: started
enabled: true
handlers:
- name: Restart nginx
ansible.builtin.service:
name: nginx
state: restartedInventory
# inventory/hosts.ini
[webservers]
web1.example.com ansible_host=10.0.0.1
web2.example.com ansible_host=10.0.0.2
[dbservers]
db1.example.com ansible_host=10.0.1.1
[webservers:vars]
http_port=80
ansible_user=deploy
[all:vars]
ansible_python_interpreter=/usr/bin/python3Useful Options
# Run playbook
ansible-playbook site.yml
# Limit to specific hosts
ansible-playbook site.yml --limit webservers
# Check mode (dry run)
ansible-playbook site.yml --check --diff
# Start at specific task
ansible-playbook site.yml --start-at-task="Deploy configuration"
# Tags
ansible-playbook site.yml --tags "deploy,config"
ansible-playbook site.yml --skip-tags "testing"
# Extra variables
ansible-playbook site.yml -e "app_version=2.2.0"
# Vault
ansible-vault create secrets.yml
ansible-vault edit secrets.yml
ansible-playbook site.yml --ask-vault-passRoles Structure
roles/
webserver/
tasks/main.yml
handlers/main.yml
templates/nginx.conf.j2
files/
vars/main.yml
defaults/main.yml
meta/main.ymlTips and Tricks
- Use
ansible-lintto check playbook quality - Use
moleculefor role testing - Use FQCN (fully qualified collection names):
ansible.builtin.copynotcopy - Use
--diffwith--checkto see what would change - Use
ansible-galaxy collection installto add community collections

