Ansible - Collapse array to variable using the join filter

join is a Jinja2 filter, which can be used to collapse an array of values into a string. Let's say you are using the vars plugin to create an array of fruit, like this.

vars:
  fruit: 
    - apple
    - banana
    - orange
    - grapes

 

The debug module can be used to output the entire array, like this.

- name: output the contents of the 'fruit' array
  debug: 
    msg: "{{ fruit }}"

 

Which should return the following.

TASK [output the contents of the 'fruit' array]
ok: [server1.example.com] => {
    "msg": [
        "apple"
        "banana",
        "orange",
        "grapes"
    ]
}

 

The join filter can be used to collapse the array.

- name: join the 'fruit' array
  debug: 
    msg: "{{ fruit | join }}"

 

Which should return the following.

TASK [join the 'fruit' array]
ok: [server1.example.com] => {
    "msg": [
        "applebananaorangegrapes"
    ]
}

 

Arguments can be passed into join. In this example, a single white space will be placed between each element.

- name: join the 'fruit' array
  debug: 
    msg: "{{ fruit | join(' ') }}"

 

Which should return the following.

TASK [join the 'fruit' array]
ok: [server1.example.com] => {
    "msg": [
        "apple banana orange grapes"
    ]
}

 



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 6543e 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   |