Bootstrap FreeKB - Ansible - Convert a string into an list using the list filter
Ansible - Convert a string into an list using the list filter

Updated:   |  Ansible articles

Let's say you are using the vars plugin to create a variable named "greeting" that contains string "Hello World". The debug module can be used to print the variable.

---
- hosts: localhost
  vars:
    greeting: Hello World
  tasks:
  - debug:
      var: greeting
...

 

Which should produce the following.

ok: [localhost] => {
    "greeting": "Hello World"
}

 

list can be used to convert the string into a list.

---
- hosts: localhost
  vars:
    greeting: Hello World
  tasks:
  - debug:
      var: greeting | list
...

 

By default, each character in the string will be a unique element in the list.

ok: [localhost] => {
    "greeting | list": [
        "H", 
        "e", 
        "l", 
        "l", 
        "o", 
        " ", 
        "W", 
        "o", 
        "r", 
        "l", 
        "d"
    ]
}

 

Typically, this is not what you are looking for. Instead, you probably want each word in the string to be an element in the list. split can be used to split the string into elements in a list.

---
- hosts: localhost
  vars:
    greeting: Hello World
  tasks:
  - debug:
      var: greeting.split()
...

 

Which should return the following.

ok: [localhost] => {
    "greeting.split()": [
        "Hello", 
        "World"
    ]
}

 




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