Programming
yaml ansible ansible-playbook
Updated Thu, 11 Aug 2022 05:48:50 GMT

Ansible fileinline not working with loop


I am trying to add or edit multiple lines in a file using lineinfile but not working. I am using below code with no luck Ref: ansible: lineinfile for several lines?

# vim /etc/ansible/playbook/test-play.yml 
- hosts: tst.wizvision.com
  tasks:
  - name: change of line
    lineinfile:
      dest: /root/test.txt
      regexp: "{{ item.regexp }}"
      line: "{{ item.line }}"
      backrefs: yes
      with_items:
      - { regexp: '^# line one', line: 'NEW LINE ONE' }
      - { regexp: '^# line two', line: 'NEW LINE TWO' }

Ansible Error:

# ansible-playbook test-2.yml

TASK [change of line] **********************************************************

fatal: [localhost]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'item' is undefined\n\nThe error appears to have been in '/etc/ansible/playbook/test-2.yml': line 3, column 5, 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: change of line\n ^ here\n"}




Solution

Your with_items is not indented correctly within the task.

with_items should be at the level of the module, not as a parameter to the module itself. In your case, you are passing with_items as a parameter to lineinfile module, and ansible is complaining that there is no parameter as with_items for lineinfile module.

Your task should look something like this -

tasks:
- name: change of line
  lineinfile:
    dest: /root/test.txt
    regexp: "{{ item.regexp }}"
    line: "{{ item.line }}"
    backrefs: yes
  with_items:
    - { regexp: '^# line one', line: 'NEW LINE ONE' }
    - { regexp: '^# line two', line: 'NEW LINE TWO' }






External Links

External links referenced by this document: