Ansible for Services and systemd
Services are two separate facts: is it running now (state) and does it start at boot (enabled). The exam almost always asks for both, and a grader reboots or checks systemctl is-enabled.
yaml - hosts: webservers tasks: - ansible.builtin.service: name: httpd state: started stopped, restarted, reloaded enabled: true
ansible.builtin.systemdservice (alias systemd) adds systemd-only options: daemonreload: true after you drop a unit file, masked: true, and scope: user.
yaml - ansible.builtin.copy: dest: /etc/systemd/system/webasha-heartbeat.service content: | [Service] ExecStart=/usr/bin/sleep infinity [Install] WantedBy=multi-user.target - ansible.builtin.systemdservice: name: webasha-heartbeat daemonreload: true state: started enabled: true
Handlers. Restarting on every run is wasteful and sometimes harmful. Notify a handler from the task that changes the config; it runs once at the end of the play, only if something changed:
yaml tasks: - ansible.builtin.template: { src: httpd.conf.j2, dest: /etc/httpd/conf/httpd.conf } notify: restart httpd handlers: - name: restart httpd ansible.builtin.service: { name: httpd, state: restarted }
The notify string must match the handler name exactly. A failing task later in the play stops handlers from running unless you use --force-handlers or meta: flushhandlers.
Default target. There is no module for systemctl set-default; a file task that links /etc/systemd/system/default.target to the wanted target does it idempotently.
Checking your work. ansible webservers -m command -a 'systemctl is-enabled httpd' and ansible dev,test -m command -a 'systemctl is-active httpd' (which should report inactive, a non-zero exit) confirm both halves without logging in. Keep service plays near the package plays that install the software, since starting a service whose package is missing fails with Could not find the requested service. When a task says the service must also be reachable, remember the firewall: a running httpd behind a closed port 80 still scores nothing.
Pitfalls. state: started alone (not enabled). Starting a service whose package is not installed on that group. Forgetting daemonreload after writing a unit. Stopping a service on "all" when the task names only one environment.