Bootstrap FreeKB - Ansible - Remove duplicates from a list
Ansible - Remove duplicates from a list

Updated:   |  Ansible articles

Let's say you have a list that contains duplicates. In this example, the fruits lists contains "apple" three times. unique can be used to remove duplicates from a list.

---
- hosts: localhost
  vars:
    fruits:
      - apple
      - banana
      - apple
      - orange
      - apple
      - grapes
  tasks:
  - debug:
      var: fruits

  - name: remove duplicates
    set_fact:
      fruits: "{{ fruits | unique }}"

  - name: fruits list with duplicates removed
    debug:
      var: fruits
...

 

Something like this should be returned.

ok: [localhost] => {
    "fruits": [
        "apple",
        "banana",
        "apple",
        "orange",
        "apple",
        "grapes"
    ]
}

TASK [remove duplicates] 
ok: [localhost]

TASK [fruits list with duplicates removed] 
ok: [localhost] => {
    "fruits": [
        "apple",
        "banana",
        "orange",
        "grapes"
    ]
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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