Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...