Ansible: Raise Error if replace did not find anything to replace

How do you solve this in Ansible?

I have a file /etc/foo/foo.config. I want to replace the string "DisallowBar" to "AlllowBarUntilMidnight" in this file.

Ansible should act in these cases like this:

  • Case1: DisallowBar gets found and gets replaced: OK
  • Case2: AllowBarUntilMidnight is already in the file. Nothing gets done: OK
  • Case3: DisallowBar and AllowBarUntilMidnight are not in the file: I want ansible to fail.

Case3 is important for me, since this state should not exist. It is an error and this should not pass silently.


You can use a validate parameter of replace to ensure that the file that would be written contains AllowBarUntilMidnight and no longer contains DisallowBar.

tasks:
- name: replace DisallowBar 
  replace:
    path: /etc/foo/foo.config
    regexp: 'DisallowBar'
    replace: "AllowBarUntilMidnight"
    validate: 'grep "AllowBarUntilMidnight" %s'

The validate command runs on the generated temporary file before it is copied into place after the replace runs. In this case, if the grep fails, it means no replacement took place, and your original file never contained DisallowBar to begin with. The play then fails and the file is unchanged.


You can simply rely on the default behavior of the replace function to ensure that the file won't contain the string DisallowBar anymore.

After that replace task has run you only need to confirm that the file does contain the string AllowBarUntilMidnight and raise an error if it doesn't. You can do that with a simple grep.

  tasks:
  - name: replace DisallowBar 
    replace:
      path: /etc/foo/foo.config
      regexp: 'DisallowBar'
      replace: "AllowBarUntilMidnight"

  - name: Check for AllowBarUntilMidnight setting
    shell: grep "AllowBarUntilMidnight"  /etc/foo/foo.config