Q: "Does anyone know what is wrong with this code?"
A: First, the is a syntax error
template error while templating string: expected token 'end of print statement', got 'item'. String: {{ kill item }}. expected token 'end of print statement', got 'item'"
the cmd
should be
shell: "kill {{ item }}"
Despite of the question looks like a duplicate of How to kill running process using Ansible or How force kill process and exit from ansible-playbook if not successful?, you may try the specific Ansible module in this case, here pids
module – Retrieves process IDs list if the process is running otherwise return empty list.
---
- hosts: localhost
become: true
gather_facts: false
tasks:
- name: Getting process IDs of the process
community.general.pids:
name: httpd
register: pids_of_httpd
- name: Force kill the processes
shell:
cmd: "kill -9 {{ item }}"
loop: "{{ pids_of_httpd }}"
Furthermore you should try to just simply stop the processes via service
module – Manage services.
---
- hosts: localhost
become: true
gather_facts: false
tasks:
- name: Stop service httpd, if started
service:
name: httpd
state: stopped