If you are not familiar with modules, check out Ansible - Getting Started with Modules.
The systemd module is used to start, stop, restart, reload, enable, and disable systemd services on the managed node (e.g. the target system).
become is used to run the command as root.
In this example, the nginx web server will be stopped and disabled.
- name: stop nginx
systemd:
name: nginx
state: stopped
enabled: no
become: yes
become_user: root
In this example, the nginx web server will be started and enabled.
- name: stop nginx
systemd:
name: nginx
state: started
enabled: yes
become: yes
become_user: root
Or to restart.
- name: restart nginx
systemd:
name: nginx
state: restarted
become: yes
become_user: root
If you have added a new systemd service, daemon_reload can be used so that systemd detects the new service.
- name: reload systemd daemons
systemd:
daemon_reload: yes
If the service was successfully stopped, started, restated, or reloaded, the play should indicate changed.
TASK [stop nginx]
changed: [server1.example.com]
Masked
The masked option can be used to mask (or unmask) a service. When masked, it is impossible to start the service.
- name: stop, disable and mask nginx
systemd:
name: nginx
state: stopped
enabled: false
masked: true
Arguments
Additional arguments can be included. For example, with the service command, here is how you would include the "foo" argument.
systemctl start nginx foo
And here is how to do the same in Ansible.
- name: stop nginx
systemd:
name: nginx
state: started
enabled: yes
arguments: foo
become: yes
become_user: root