← All cheatsheets

IaC

Ansible — playbook + ad-hoc command quickref

## Ad-hoc commands
`ansible all -i inventory -m ping` — ping every host
`ansible web -i inv -m shell -a "uptime"` — run a shell command on `web` group
`ansible all -i inv -m apt -a "name=nginx state=present" -b` — install nginx (become)
`ansible all -i inv -m service -a "name=nginx state=restarted" -b` — restart service
`ansible all -i inv -m copy -a "src=./file dest=/etc/file" -b` — copy file

## Playbook commands
`ansible-playbook -i inventory playbook.yml` — run playbook
`ansible-playbook -i inv playbook.yml --check` — dry run (no changes)
`ansible-playbook -i inv playbook.yml --diff` — show what would change
`ansible-playbook -i inv playbook.yml --limit web` — only `web` group
`ansible-playbook -i inv playbook.yml --tags deploy` — only tagged tasks

## Vault (secrets in playbooks)
`ansible-vault encrypt vars.yml` — encrypt a vars file
`ansible-vault edit vars.yml` — edit encrypted file in place
`ansible-playbook -i inv playbook.yml --ask-vault-pass` — prompt for vault password
`ansible-playbook -i inv playbook.yml --vault-password-file=.vault` — non-interactive

## Inventory format
Plain text (`inventory.ini`): `[web]\nweb01\nweb02\n[db]\ndb01`
YAML (`inventory.yml`): structured groups with vars

## Tip
For learning, use ad-hoc commands until they get unwieldy, then graduate to playbooks.