1
votes

I am trying to create multiple files with some sample contents in ansible. Below is my playbook file. --- # create a file and copy it - hosts: remote become: yes remote_user: root

  tasks:
   - name: create multiple files
     copy:
      dest: "{{ item }}"
      content: |
         It is sample file
      with_items:
        -  Test1.txt
        -  Test2.txt
        -  Test3.txt

When i execute it ,i get the below error. Tried multiple ways but no luck. How to create multiple file with some sample contents?

fatal: [Mymachine.com]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'item' is undefined\n\nThe error appears to have been in '/myshare/myuser/playbooks/multifile.yml': line 7, column 6, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n tasks:\n
- name: create multiple files\n ^ here\n"}

2

2 Answers

2
votes

With_items shall be in the level of the command copy:

tasks:
   - name: create multiple files
     copy:
      dest: "{{ item }}"
      content: |
         It is sample file
     with_items:
       -  Test1.txt
       -  Test2.txt
       -  Test3.txt
1
votes

Use template. See example below

tasks:
  - template:
      src: template.j2
      dest: "{{ item }}"
    loop:
      -  Test1.txt
      -  Test2.txt
      -  Test3.txt

.

# cat template.j2
It is sample file