Best practices for writing better ansible playbooks


Some of the best practices for writing the clean and scalable ansible playbooks:
  1. Maintain all ansible code in git.
  2. Maintain the standard directory structure. Here is the reference: https://github.com/Indu-sharma/learningansible
  3. Use requirements.txt for python dependencies management and requirements.yml for ansible-galaxy modules/roles.
  4. Configure ansible_stdout_callback, log file path, forks in ansible.cfg.
  5. Always use -check mode for ansible playbooks for the dry run. 
  6. Verify all your variables in advance with -m setup.
  7. Use ansible-galaxy init for your creating your roles directory/files structures.
  8. Within a role playbook, follow the sequence in the start
    • Use assert to check that requirements are met
    • Install packages
    • Use Validate for Template config files 
    • Trigger handlers when config files have been changed  
  9. Avoid using shell/command modules if possible; they are skipped in -check mode.
  10. Avoid using set_facts; they are not visible when using -m setup mode. Also, variables are not while using --start-at option.
  11. Use Tags as much as possibles.
  12. Don't hide changes(when using --diff/-check )
  13. Don't suppress failures. 
  14. Ensure Idem-potency always. 
  15. Don't hard code any variables in playbooks.
  16. Use Dynamic Inventory wherever possible
  17. Use strategy as Debug in the playbooks.
  18. Use Mitogen or Pipe-lining to speed up the playbooks run time. 
  19. Use Molecule module to test the playbooks.






Comments