Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have many lines need to add, like

  1. today
  2. is
  3. a
  4. good
  5. day

if just one dest, will be

- name: add line
  lineinfile:
    dest: "/tmp/aaa.txt"
    line: "{{ item }}"
  with_items:
    - "toady"
    - "is"
    - "a"
    - "good"
    - "day"

and then, also have many files need to add, like

  1. aaa.txt
  2. bbb.txt
  3. ccc.txt

if just one line, will be

- name: add line
  lineinfile:
    dest: "{{ item }}"
    line: "today"
  with_items:
    - "/tmp/aaa.txt"
    - "/tmp/bbb.txt"
    - "/tmp/ccc.txt"

Now I need mix them, both have all dest and all line, but I can't try it success.

Both of them are an array or object, I try many method still fail.

Helppppppp please :(

Thanks everyone

question from:https://stackoverflow.com/questions/65934597/ansible-lineinfile-how-add-multiple-lines-with-multiple-dest

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

Use nested. For example

- hosts: localhost
  vars:
    files: [aaa.txt, bbb.txt, ccc.txt]
    lines: [today, good, day]
  tasks:
    - lineinfile:
        create: true
        dest: "/tmp/{{ item.0 }}"
        line: "{{ item.1 }}"
      with_nested:
        - "{{ files }}"
        - "{{ lines }}"

gives

shell> cat /tmp/aaa.txt 
today
good
day

shell> cat /tmp/bbb.txt 
today
good
day

shell> cat /tmp/ccc.txt 
today
good
day

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...