为什么ansible忽略了lineinfile中的这个正则表达式?

时间:2015-03-18 14:01:42

标签: regex ansible ansible-playbook

我试图告诉ansible在/etc/hosts.deny中添加“ALL:ALL”行,只要该行不存在。这是我的任务:

- name: Ensure hosts.deny has default ALL entry
  lineinfile: dest="/etc/hosts.deny" regexp="^\s*ALL\s*:" line="{{ deny_all }}" insertbefore=EOF

这一切都称为合规性,因此在合规性/ vars / main.yml中,我有:

deny_all: 'ALL : ALL'

这是为了解决那里单独冒号的解析器问题。

我也试过这些正则表达式,但没有快乐:

  • “^ \ S * ALL”
  • “ALL”
  • “FOO”

我用一个完全空的文件替换了现有的/etc/host.deny,但每次运行它时,此任务仍会返回“ok”。我错过了什么?我确定这是非常痛苦的事情,但我只是没有看到它。

感谢。

---编辑了新的细节---

我修改了原始任务,现在看起来像这样:

- name: Ensure hosts.deny has default ALL entry
  lineinfile: dest='/etc/hosts.deny' line='ALL' insertbefore=EOF create=True state=present

然后我从远程系统删除了 /etc/hosts.deny。运行此任务(通过标签)会产生“ok”而不是创建文件:

# ansible-playbook compliance -i inventory.yml --tags deny -l us202

PLAY [Compliance] *******************************************

TASK: [Ensure /etc/hosts.deny has default ALL entry *********
ok: [us202]

PLAY RECAP **************************************************
us202         : ok=1   changed=0   unreachable=0   failed=0

#

这怎么可能?

2 个答案:

答案 0 :(得分:2)

问题是我误读了文档并使用了insertbefore = EOF,而不是insertafter = EOF。当我切换到insertafter = EOF时,它没有问题。

答案 1 :(得分:1)

lineinfile模块中的冒号存在一般问题。我找到了this thread on the mailing list

如果line包含冒号,则需要对所有内容进行双引号或以多行YML语法编写。

双引号:

- name: Ensure hosts.deny has default ALL entry
  lineinfile: 'dest="/etc/hosts.deny" line="ALL {{":"}} ALL"'

多:

- name: Ensure hosts.deny has default ALL entry
  lineinfile: >
    dest="/etc/hosts.deny"
    line="ALL {{':'}} ALL"

多行语法中的>非常重要。


上一个回答:

你的线条似乎非常静态。是否需要正则表达式,而问题中没有提到?如果没有,你可以简单地删除它,然后Ansible将搜索确切的行 - 不需要正则表达式。

如果行可以变化并且您需要通过模式识别它,则需要正则表达式,例如设置foo,其值未定义/未知。

另一方面,有一个技巧可以避免使用冒号解析错误:您只需在YML中使用{{':'}}即可。这归功于github user drewp

相关问题