Issue
I'm trying to concatentate an Ansible list into a space seperate string without surrounding quotes within a shell or command module call.
The command I'm trying to use requires a space separated list of variables only.
So with the list:
somelist:
- item1
- item2
We can build the shell module task:
- name: Execute a command
ansible.builtin.shell: >
/some/command {{ somelist | split(' ') }}
Which translates on the actual command to:
/some/command 'item1 item2'
However, the command in question requires a space separated list of variables, not a string - such as:
/some/command item1 item2
I could use loop but that produces a list of dictionaries in the captured results which I then can't use as a conditional for the when: clause on the task.
Is there some way to convert the Ansible list to the above format?
Solution
We can build the shell module task:
- name: Execute a command ansible.builtin.shell: > /some/command {{ somelist | split(' ') }}
Which translates on the actual command to:
/some/command 'item1 item2'
Actually no. A simple test would just fail with
TASK [Execute a command] ******************************************************************
fatal: [localhost]: FAILED! =>
msg: |-
Unexpected templating type error occurred on (/some/command {{ somelist | split(' ') }}
): descriptor 'split' requires a 'unicode' object but received a 'list'
In order to concatenate a list of items one will need to join
them.
A minimal example playbook
---
- hosts: localhost
become: false
gather_facts: false
vars:
somelist:
- item1
- item2
tasks:
- shell:
cmd: "echo {{ somelist | join(' ') }}"
register: result
- debug:
var: result
will result into an output of
TASK [debug] *************************
ok: [localhost] =>
result:
changed: true
cmd: echo item1 item2
delta: '0:00:00.013335'
end: '2023-11-23 12:30:00.013334'
failed: false
msg: ''
rc: 0
start: '2023-11-23 12:30:00.000000'
stderr: ''
stderr_lines: []
stdout: item1 item2
stdout_lines:
- item1 item2
Documentation Example
-
To concatenate a list into a string:
{{ list | join(" ") }}
Answered By - U880D Answer Checked By - Candace Johnson (WPSolving Volunteer)