Bootstrap FreeKB - Ansible - Convert a string into an list using the split filter
Ansible - Convert a string into an list using the split 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"
}

 

split can be used to convert the string into a list containing the elements. By default, split will split elements where there is whitespace.

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

 

Which should return the following.

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

 


Specify an item

Each item will have an index number, like this.

  • 0 = Hello
  • 1 = World

Here is how to output a specific item.

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

  - debug:
      var: greeting.split()[1]
...

 

Which should return the following.

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

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

 


Specify a delimiter

Let's say you have the following variable.

foo: "hello.world.how.are.you"

 

split can be used to separate the fields at a delimiter. In this example, the . (period) delimiter is used.

- name: print field 0
  debug:
    var: foo.split('.')[0]

 

Which should return the following.

TASK [print field 0]
ok: [server1.example.com] => {
    "foo.split('.')[0]": "Hello"
}

 


Register parameter

Let's say you use the register parameter to capture output, like this.

- name: list the contents of the /tmp directory
  shell: ls /tmp
  register: out

 

Here is how you would use split with register output.

- name: split at a single whitespace, print field 1
  debug:
    msg: "{{ out.stdout.split(' ')[0] }}"

 

The set_fact module can be used to create a variable that contains the split value.

- set_fact:
    value: "{{ out.stdout.split(' ')[0] }}"

 




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