Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ansible – Concatenate list of items for command module without surrounding quotes

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading