Ansible - Cut a string into pieces using the split filter

Let's say you are using the vars plugin to create a variable, like this.

vars:
  foo: "Hello World"

 

Or the set_fact module, like this.

- set_fact: 
    foo: "Hello World"

 

The debug module can be used to print the variable. Notice the double curley braces {{ ... }}. Jinja2 uses double curley braces for variables.

- name: output the content of the 'foo' variable
  debug:
    var: foo

 

Which should produce the following.

TASK [output the content of the 'foo' variable]
ok: [server1.example.com] => {
    "foo": "Hello World"
}

 

split can be used to separate the fields. By default, split will split fields where there is whitespace.

- name: split the 'foo' variable
  debug:
    var: foo.split()

 

Which should return the following.

TASK [print field 0]
ok: [server1.example.com] => {
    "foo.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.

- name: split the 'foo' variable and print item 0
  debug:
    var: foo.split()[0]

 

Which should return the following.

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

 


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] }}"

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |