2016-09-19 53 views
0

我想在文件中使用lineinfile添加或編輯多行但不起作用。我使用下面的代碼,沒有運氣編號:ansible: lineinfile for several lines?Ansible fileinline不能與循環一起工作

# 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錯誤:

# ansible-playbook test-2.yml 

TASK [線的變化] ************** ********************************************

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"}

回答

2

您的with_items未在任務中正確縮進。

with_items應該在模塊級別,而不是作爲模塊本身的參數。在你的情況下,你通過with_items作爲參數lineinfile模塊,並ansible抱怨with_items沒有參數爲lineinfile模塊。

你的任務應該是這個樣子 -

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' } 
+0

非常感謝。它現在有效。浪費了我很多時間...... –

+0

沒問題,很高興它爲你工作! :) – rk2