Junior — Middle
Could you describe your experience with handlers and templates in Ansible for automation tasks?
sobes.tech AI
Answer from AI
In Ansible, handlers are special tasks that are executed only when there is a change in state, such as restarting a service after a configuration change.
Templates allow for dynamically creating configuration files based on variables, using Jinja2.
Experience of application:
- Used handlers to restart services (nginx, systemd) only when configuration files changed, which increased efficiency and prevented unnecessary restarts.
- Applied templates to generate configurations considering the environment (dev, prod), enabling maintenance of a single playbook for different environments.
Example of a handler:
handlers:
- name: restart nginx
service:
name: nginx
state: restarted
Example of calling a handler in a task:
tasks:
- name: update nginx config
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: restart nginx
This approach helps automate configuration and service management efficiently and safely.