JackTheKnife
JackTheKnife

Reputation: 4144

Ansibe: concatenation of items from with_items

I'm trying to get a variable which will contain comma separated items from with_itmes loop as follow:

- hosts: localhost
  connection: local
  gather_facts: no

  tasks:
    - name: set_fact
      set_fact:
        foo: "{{ foo }}{{ item }},"
      with_items:
        - "one"
        - "two"
        - "three"
      vars:
        foo: ""

    - name: Print the var
      debug:
        var: foo

It works as expected but what I'm getting at the end is trailing comma.

Is there any way to remove it?

Upvotes: 0

Views: 517

Answers (2)

seshadri_c
seshadri_c

Reputation: 7340

There is a join filter that we can use with lists to concatenate list elements with a given character.

If we are passing the list directly to with_items or loop then we can use loop_control to "extend" some more loop information to get ansible_loop.allitems. Then this can be joined with the join filter.

Example:

  - set_fact:
      foo: "{{ ansible_loop.allitems|join(',') }}"
    loop:
    - one
    - two
    - three
    loop_control:
      extended: true

Otherwise a more straightforward way is to define a variable with list and use join filter on elements of that variable.

Example:

  - set_fact:
      foo: "{{ mylist|join(',') }}"
    vars:
      mylist:
      - one
      - two
      - three

Upvotes: 1

JackTheKnife
JackTheKnife

Reputation: 4144

No clue if this is correct way to do but it does the job:

    - name: Print the var
      debug:
        msg: "LIST: {{ foo | regex_replace(',$','') }}"

Upvotes: 0

Related Questions