Ansible — Theory
Ansible — Theory (concise)
Section titled “Ansible — Theory (concise)”Idempotency philosophy
Section titled “Idempotency philosophy”Modules report ok / changed / failed. Re-running playbooks should converge without unintended changes. command/shell break this guarantee — use creates: / changed_when: to fix.
Push vs pull
Section titled “Push vs pull”- Ansible is push by default — control node SSHes to targets.
- Ansible Pull mode: hosts pull from git. Used in immutable/edge contexts.
- Compare to Puppet / Chef / Salt — agent-based pull.
Idempotent task examples
Section titled “Idempotent task examples”- name: only run if file missing shell: ./bootstrap.sh args: { creates: /opt/.bootstrapped }
- name: run + interpret success shell: kubectl apply -f manifest.yml register: kubectl_out changed_when: "'configured' in kubectl_out.stdout or 'created' in kubectl_out.stdout"Roles for reuse
Section titled “Roles for reuse”- Per concern:
nginx,postgres,monitoring. - Use Ansible Collections for distribution (replaces older Galaxy roles).
- Pin versions in
requirements.yml.
Performance
Section titled “Performance”- SSH multiplexing on (default).
mitogenstrategy plugin — significant speedup.forks: Nparallelism.gather_facts: falseif not needed.- Use
asyncfor long tasks running in parallel.
When to choose Ansible vs Terraform
Section titled “When to choose Ansible vs Terraform”- Terraform — provisioning cloud resources (VMs, networks, IAM).
- Ansible — configuring inside the resources (install packages, files, services).
Often used together: TF creates VMs, Ansible configures them. Or use cloud-init for first-boot config and Ansible for subsequent changes.
Common interview Qs
Section titled “Common interview Qs”- Why might a task report changed=true on every run? Non-idempotent module (shell/command without changed_when), or the resource keeps drifting.
- How to handle secrets in Ansible? Vault, or fetch from KMS at runtime via lookup.
- Rolling restart 50 servers without outage.
serial: 5,max_fail_percentage, drain LB before restart. - What’s a handler — when does it run? End of play, only if notified by a changed task. Use to restart services after config changes.
- Difference role vs collection? Collection is the modern bundle (modules + plugins + roles); role is just tasks/handlers.
- When NOT use Ansible? K8s reconciliation; immutable infra; very large fleets.
- Test playbooks? Molecule (containers as test hosts), syntax-check, ansible-lint.
Anti-patterns
Section titled “Anti-patterns”command/shelleverywhere instead of modules.- Hard-coded paths, secrets in playbooks.
- One playbook for everything → unmaintainable.
- Skipping
--checkbefore applying. - Mixing config and one-off ops in same play.
- Storing inventory in code without protecting credentials.