Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

ansible - 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?

question from:https://stackoverflow.com/questions/65852013/ansibe-concatenation-of-items-from-with-items

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...