How to delete Ansible host entries from hosts file using Ansible

How to delete Ansible host entries from hosts file using Ansible

In #Ansible we run an #Ansible play against a target hosts group, the #Ansible play will be executed on each remote host that is part of that particular target group.

Lets say we want to pass the host details dynamically to host file and every time we run a play we want to run them on new host passed dynamically.

In order to achieve this there are multiple ways lets discuss the one way of doing it.

we should remove the host’s entries from /etc/ansible/hosts file each time before running any #Ansible play. Below #Ansible-play which will remove the host entries and replace them with a blank line

ansible-play.yml

---- hosts: localhostbecome: truetasks:- name: loop debug inventory hostnames  debug:    msg: "{{ item }}"  with_inventory_hostnames: ameyo  register: hostip- name: remove host ip's  lineinfile:    path: /etc/ansible/hosts    regexp: "{{item}}"    line: ''  with_inventory_hostnames: <target_grouo_name>