Bootstrap FreeKB - Ansible - Combine or Merge a List using plus or zip
Ansible - Combine or Merge a List using plus or zip

Updated:   |  Ansible articles

If you are not familar with list, check out Ansible - Getting Started with Lists.

Let's say you are using the set_fact module to create two different lists, fruit and veggy. The debug module can be used to output the entire list, like this.

---
- hosts: localhost
  tasks:
  - set_fact:
      fruit: [ apple, banana, orange, grapes ]
      veggy: [ onion, pepper, tomato, carrot ]

  - debug: 
      var: fruit

  - debug: 
      var: veggy
...

 

Which should return the following.

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

ok: [localhost] => {
    "veggy": [
        "onion"
        "pepper",
        "tomato",
        "carrot"
    ]
}

 

Here is how you could combine or merge these lists into a new list.

---
- hosts: localhost
  tasks:
  - set_fact:
      fruit: [ apple, banana, orange, grapes ]
      veggy: [ onion, pepper, tomato, carrot ]

  - set_fact:
      food: "{{ fruit + veggy }}"

  - debug: 
      var: food
...

 

Which should return the following.

ok: [localhost] => {
    "food": [
        "apple"
        "banana",
        "orange",
        "grapes",
        "onion"
        "pepper",
        "tomato",
        "carrot"
    ]
}

 

Or like this, using zip and list.

---
- hosts: localhost
  tasks:
  - set_fact:
      fruit: [ apple, banana, orange, grapes ]
      veggy: [ onion, pepper, tomato, carrot ]

  - set_fact:
      food: "{{ fruit | zip(veggy) | list}}"

  - debug:
      var: food
...

 

Which should produce the following.

ok: [localhost] => {
    "food": [
        [
            "apple", 
            "onion"
        ], 
        [
            "banana", 
            "pepper"
        ], 
        [
            "orange", 
            "tomato"
        ], 
        [
            "grapes", 
            "carrot"
        ]
    ]
}

 

If you want to include additional strings, you may have to use an approach like this.

---
- hosts: localhost
  tasks:
  - set_fact:
      fruit: [ apple, banana, orange, grapes ]
      veggy: [ onion, pepper, tomato, carrot ]

  - set_fact:
      food: []

  - set_fact:
      food: "{{ food }} + ['/tmp/{{ item }}']"
    with_items:
    - "{{ fruit }}"
    - "{{ veggy }}"

  - debug: 
      var: food
...

 

Which should return the following.

ok: [localhost] => {
    "food": [
        "/tmp/apple"
        "/tmp/banana",
        "/tmp/orange",
        "/tmp/grapes",
        "/tmp/onion"
        "/tmp/pepper",
        "/tmp/tomato",
        "/tmp/carrot"
    ]
}



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 2bbf4b in the box below so that we can be sure you are a human.