Ansible - systemd module (start stop restart services)

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

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





Please enter 74099 in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |