Skip to content

~/avetyan.com/cheatsheets

Cheat sheets

Ansible cheat sheet

Ad-hoc commands, inventories, playbook flags, check and diff mode, tags, limits and Vault: the Ansible commands I run every day.

2 min read


Ad-hoc commands

bash
ansible all -i inventory.ini -m ping
ansible web -m shell -a 'uptime'
ansible web -m apt -a 'name=nginx state=latest' --become
ansible web -m service -a 'name=nginx state=restarted' -b
ansible db -m setup -a 'filter=ansible_memtotal_mb'       # facts
ansible all -m copy -a 'src=motd dest=/etc/motd' -b

Inventory

inventory.ini
[web]
web1.example.com
web2.example.com ansible_port=2222

[db]
db1.example.com ansible_user=admin

[prod:children]
web
db
bash
ansible-inventory -i inventory.ini --graph
ansible-inventory -i inventory.ini --host web1.example.com
ansible -i inventory.ini prod --list-hosts

Running playbooks

bash
ansible-playbook -i inventory.ini site.yml
ansible-playbook site.yml --check --diff          # dry run with file diffs
ansible-playbook site.yml --limit web1.example.com
ansible-playbook site.yml --tags nginx
ansible-playbook site.yml --skip-tags slow
ansible-playbook site.yml --start-at-task 'Install packages'
ansible-playbook site.yml --step                  # confirm each task
ansible-playbook site.yml -e 'version=1.4.2'

Playbook flags

FlagWhat it does

Vault

bash
ansible-vault create secrets.yml
ansible-vault edit secrets.yml
ansible-vault encrypt vars/prod.yml
ansible-vault view secrets.yml
ansible-vault rekey secrets.yml
ansible-vault encrypt_string 's3cr3t' --name db_password
ansible-playbook site.yml --ask-vault-pass
ansible-playbook site.yml --vault-password-file ~/.vault_pass

Roles

bash
ansible-galaxy role init roles/nginx
ansible-galaxy install -r requirements.yml
ansible-galaxy collection install community.general
ansible-doc apt                          # module docs offline
ansible-doc -l | grep postgres

Debugging

bash
ansible-playbook site.yml -vvv
ANSIBLE_KEEP_REMOTE_FILES=1 ansible-playbook site.yml   # keep generated module files on the host
ansible-lint site.yml
yaml
- ansible.builtin.debug:
    var: ansible_facts.default_ipv4

Keep in mind

  • Prefer modules over shell/command: modules are idempotent and report “changed” honestly.
  • Run with --check --diff before any change on production hosts.
  • Set forks and pipelining = True in ansible.cfg; pipelining makes runs noticeably faster.

Comments

Sign in with Google, GitHub or Facebook to comment.

Loading comments…