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