首页 文章

Ansible fileinline无法使用循环

提问于
浏览
0

我正在尝试使用 lineinfile 在文件中添加或编辑多行但不起作用 . 我使用下面的代码没有运气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

任务[换行] ******************************************** **************

致命:[localhost]:失败! => {“failed”:true,“msg”:“字段'args'的值无效,似乎包含一个未定义的变量 . 错误是:'item'未定义\ n \ n出现错误已经在'/etc/ansible/playbook/test-2.yml':第3行,第5列,但可能在文件的其他位置,具体取决于确切的语法问题 . \ n \ n违规行似乎是:\ n \ n任务:\ n - 名称:换行\ n ^这里\ n“}

1 回答

  • 3

    您的 with_items 未在任务中正确缩进 .

    with_items 应该在模块的级别,而不是模块本身的参数 . 在您的情况下,您将 with_items 作为参数传递给 lineinfile 模块,并且ansible抱怨 lineinfile 模块没有参数 with_items .

    你的任务应该是这样的 -

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

相关问题