## Best Practices ### 1. **Idempotency** Use modules that ensure idempotency (e.g., `service`, `package`, `file`): ```yaml - name: Ensure Apache is running service: name: apache2 state: started enabled: yes ``` ### 2. **Playbook Structure** - Separate tasks into logical sections using `block`/`rescue` - Use `handlers` for services/configuration management: ```yaml - name: Restart Apache service: name: apache2 state: restarted handlers: - name: Restart Apache service: name: apache2 state: restarted ``` ### 3. **Inventory Management** - Use `ansible-inventory --list` to validate inventory structure - Leverage dynamic inventory for cloud environments (e.g., AWS, OpenStack) ### 4. **Security** - Store secrets in Ansible Vault: ```bash ansible-vault encrypt_string --vault-id myvault@prompt 'secret_value' ``` - Use `become: yes` for privileged tasks and restrict SSH access ### 5. **Testing** - Always use `--check` to simulate changes: ```bash ansible-playbook site.yml --check ``` - Use `--diff` to review changes: ```bash ansible-playbook site.yml --diff ``` ### 6. **Troubleshooting** - Use `--verbosity=2` for detailed output - Debug variables with `debug` module: ```yaml - name: Show variable value debug: msg: "{{ some_variable }}" ``` ### 7. **Automation** - Use `ansible-pull` for agentless orchestration - Combine with CI/CD pipelines for automated deployments