Bootstrap FreeKB - Ansible - Convert a list in a dictionary to a string using the join filter
Ansible - Convert a list in a dictionary to a string using the join filter

Updated:   |  Ansible articles

Let's say you have a dictionary that contains a list, perhaps like this.

---
- hosts: localhost
  tasks:
  - set_fact:
      dictionary: { list: [ 'foo', 'bar' ] }

  - debug:
      var: dictionary
...

 

Which should print the following where the list is a list.

ok: [localhost] => {
    "dictionary": {
        "list": [
            "foo", 
            "bar"
        ]
    }
}

 

Typically, you can just use the join filter to convert the list to a string.

---
- hosts: localhost
  tasks:
  - set_fact:
      dictionary: { list: [ 'foo', 'bar' ] }

  - debug:
      msg: "{{ item.value|join }}"
    with_dict: "{{ dictionary }}"
...

 

Which should return the following.

ok: [localhost] => (item={u'key': u'list', u'value': [u'foo', u'bar']}) => {
    "msg": "foobar"
}

 

If the join filter used in this way fails to convert the list to a string, you can try this.

---
- hosts: localhost
  tasks:
  - set_fact:
      dictionary: { list: [ 'foo', 'bar' ] }

  - debug:
      msg: "{{ item.value|map('join')|join }}"
    with_dict: "{{ dictionary }}"
...

 




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