Ansible Remove Duplicate IP Address from the inventory host file

Viewed 45

I have a host group as stated below like that,

Inventory File:

[test]
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.1

Playbook:

---
- hosts: test
  tasks:
    - debug:
        msg: "Something to print.."

If execute the playbook, it won't execute the task on the duplicate IP Address, Simply it will skip. Because the 192.168.1.1 it will come here two times, so the duplicate entries should not be executed. How do I make this happen using ansible.

1 Answers

Q: "Remove duplicate items from the inventory file."

A: Use the utility ansible-inventory and fix the inventory. Given the inventory with duplicate entry

shell> cat hosts
[test]
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.1

Ansible ignores the duplicate hosts. For example, the playbook

shell> cat pb.yml 
- hosts: test
  gather_facts: false
  tasks:
    - debug:
        var: inventory_hostname

gives (abridged)

shell> ansible-playbook -i hosts pb.yml
...

ok: [192.168.1.1] => 
  inventory_hostname: 192.168.1.1
ok: [192.168.1.2] => 
  inventory_hostname: 192.168.1.2
ok: [192.168.1.3] => 
  inventory_hostname: 192.168.1.3

You can use the utility ansible-inventory and fix the inventory. For example, the command below will read the inventory hosts in INI format and will create hosts.yaml in YAML format

shell> ansible-inventory -i hosts --list --yaml > hosts.yaml

gives

shell> cat hosts.yaml 
all:
  children:
    test:
      hosts:
        192.168.1.1: {}
        192.168.1.2: {}
        192.168.1.3: {}
    ungrouped: {}

Now, you can use the YAML inventory. The play below will give the same results

shell> ansible-playbook -i hosts.yaml pb.yml
Related