ansible lineinfile how add multiple lines with multiple dest?

Viewed 783

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

2 Answers

Althought this looks a bit weird to me and that I think you should probably consider using blockinfile or even better a template, there is a solution to your exact question. One possibility here with the product filter:

- name: Add several lines to several files
  vars:
    lines:
      - today
      - is
      - a
      - good
      - day
    files:
      - a.txt
      - b.txt
      - c.txt
  lineinfile:
    line: "{{ item.0 }}"
    dest: "{{ item.1 }}"
  loop: "{{ lines | product(files) }}"

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
Related