Search code examples
ansibleansible-template

Ansible - convert a comma delimited string into a space delimited string with double quotes


Following the great help I got for my last question I have another :).

I have a requirement to convert the contents of the string variable: Targets

debug:
  msg:
    - "Targets: {{ targets }}"

Returns the following:

ok: [host] => {
    "msg": [
        "Targets: 10.0.1.1,10.0.1.2"

I need to be able to split the targets string and change it to a space delimited string, with each element encapsulated with a double quote. This will then be passed to another command as a parameter.

Updated for context.
I am passing the targets variable to a role which in turn launches an executable:

- import_role:
    name: run_exectable_file
  vars:
    # passing all the params here.
    - params: -a -b -c {{ targets }}
    - runtime: 3600

The executable command line needs to be:

executable.exe -a -b -c "10.0.1.1" "10.0.1.2"

Desired output:

The targets variable need to produce the target IP addresses in a space delimited string, with each element encapsulated with a double quote.

For example, the following debug output:

ok: [host] => {
    "msg": [
        "Targets: "10.0.1.1" "10.0.1.2""

I look forward to your help as always.


Solution

  • You can use Jinja to get what you want. For example

        - debug:
            msg: "Targets: {{ _targets }}"
          vars:
            _targets: |
              {% for i in targets.split(',') %}"{{ i }}" {% endfor %}
    

    gives

      msg: |-
        Targets: "10.0.1.1" "10.0.1.2"