在lineinfile中的Ansible循环

时间:2014-10-09 18:28:20

标签: vagrant ansible ansible-playbook

注释掉多行应该使用标准循环[1],如下所示:

 - name: "Allow /srv folder accessed by default. Just comment out the lines to allow."
lineinfile: dest=/etc/apache2/apache2.conf regexp={{ item.regexp }} line={{ item.line }} state=present
with_items:
  - { regexp: '#<Directory /srv/>', line: '<Directory /srv/>' }

但我收到了一个错误:

      failed: [192.168.101.101] => (item={'regexp': '#<Directory /srv/>', 'line': '<Directory /srv/>'}) => {"failed": true, "item": {"line": "<Directory /srv/>", "regexp": "#<Directory /srv/>"}} 
msg: this module requires key=value arguments (['dest=/etc/apache2/apache2.conf', 'regexp=#<Directory', '/srv/>', 'line=<Directory', '/srv/>', 'state=present'])

FATAL: all hosts have already failed -- aborting

那么如何使用多行/项目?

[1] http://docs.ansible.com/playbooks_loops.html#standard-loops

2 个答案:

答案 0 :(得分:3)

谢谢你,tedder42!你我们不仅仅是正确的。

要成为幂等,lineinfile任务需要匹配行的注释和未注释状态,所以我们启动它:^#? 因此,功能齐全的游戏将成为:

 - name: "Allow /srv folder accessed by default. Comment out the lines to allow. "
     lineinfile: 
       dest=/etc/apache2/apache2.conf 
       regexp="{{ item.regexp }}" 
       line="{{ item.line }}" 
       state=present
     with_items:
       - { regexp: '^#?<Directory /srv/>', line: '<Directory /srv/>' }
       - { regexp: '^#?\tOptions Indexes FollowSymLinks', line: '\tOptions Indexes FollowSymLinks' }
       - { regexp: '^#?\tAllowOverride None', line: '\tAllowOverride None' }
       - { regexp: '^#?\tRequire all granted', line: '\tRequire all granted' }
       - { regexp: '^#?</Directory>', line: '</Directory>'}

这实际上不是一个好主意。绝对更好的是使用带有backup = yes的副本。

答案 1 :(得分:1)

真的接近让它工作。只需在正则表达式和行周围添加引号。

 lineinfile: dest=/etc/apache2/apache2.conf regexp="{{ item.regexp }}" line="{{ item.line }}" state=present

我不完全确定,但错误消息暗示看到regexpline args有问题,所以我尝试了一些事情。

提醒一下,lineinfile有点像反模式。当您发现自己使用它时,您应该考虑切换到copytemplate

相关问题