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

Categories

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

ansible lineinfile how add multiple lines with multiple dest?

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...