To achieve the goal in Ansible it is recommended in general to use service modules, service
, sysvinit
or systemd
. In example like
---
- hosts: localhost
become: yes
become_method: sudo
gather_facts: yes
tasks:
- name: Gathering Service Facts
service_facts:
- name: Make sure service is stopped
systemd:
name: httpd
state: stopped
enabled: no
when: ("httpd.service" in services)
If you like to use the shell
_module, for me more work was necessary.
In example for nginx
get the right PID first, since there are a primary and four worker processes.
- name: Get nginx PID
shell:
cmd: "ps -C nginx -o pid --no-headers | head 1"
warn: false
changed_when: false
check_mode: false
register: nginx_pid
It would also be possible to do something like
- name: Get nginx PIDs
shell:
cmd: "pidof nginx"
warn: false
changed_when: false
check_mode: false
register: nginx_pids
- name: Show PIDs
debug:
var: nginx_pids
- name: Kill nginx
shell:
cmd: "kill -9 {{ nginx_pids }}"
...
Regarding
I would like to add the option exit from ansible-playbook run if not successful.
to end the playbook run you could use
- meta: end_play
when: condition_is_met
use fail
_module to
- name: Task has failed because of
fail:
msg: "{{ fail_message }}"
when: condition_is_met
or the assert
_module.
Regarding the exit code (EC) or return code (RC) you may have a look into How do I get the list of exit codes (and/or return codes) and meaning for a command/utility?.