Ansible:如果替换没有找到任何要替换的内容,则引发错误

gue*_*tli 1 ansible

你如何在 Ansible 中解决这个问题?

我有一个文件/etc/foo/foo.config。我想将此文件中的字符串“DisallowBar”替换为“AlllowBarUntilMidnight”。

Ansible 应该在这些情况下采取如下行动:

  • 案例 1:DisallowBar 被发现并被替换:OK
  • 案例 2: AllowBarUntilMidnight 已在文件中。什么都没做:好的
  • 案例 3:DisallowBar 和 AllowBarUntilMidnight 不在文件中:我希望 ansible 失败。

Case3 对我很重要,因为这种状态不应该存在。这是一个错误,不应无声无息地通过。

Mic*_*ton 6

您可以使用replacevalidate参数来确保将要写入的文件包含和不再包含.AllowBarUntilMidnightDisallowBar

tasks:
- name: replace DisallowBar 
  replace:
    path: /etc/foo/foo.config
    regexp: 'DisallowBar'
    replace: "AllowBarUntilMidnight"
    validate: 'grep "AllowBarUntilMidnight" %s'
Run Code Online (Sandbox Code Playgroud)

validate命令在生成的临时文件上运行,然后在replace运行后将其复制到位。在这种情况下,如果grep失败,则意味着没有进行替换,并且您的原始文件从未包含DisallowBar在内。然后播放失败,文件不变。