I have a system under high usage load which is sensitive to partially written files. Basically you can imagine the file as a blacklist, because of the high load some requests might bypass the blacklist if there is ever an instant where ansible.builtin.template has partially written the file.
Obviously the workaround for this is to generate the file under a different filename and then rename it into place. However I don’t know how ansible.builtin.template functions internally. Does it already do something like this? Does the workaround make sense?
Basically what I’m asking is if ansible.builtin.template overwrites the file instantly, or will it truncate the file and then start writing the new file according to the loops in the template file?
The template action templates the file on the controller, and then uses the copy action to copy the templated file to the controller. The copy action essentially copies the file over to a temp file, and then essentially calls the copy module to atomically move the file to its final destination. So the replacement should be instant.
File alteration actions in Ansible should be using the ‘atomic_move’ function.
This function works as felix already explained, there is a case in which it writes directly to the file as a fallback, but only if you pass the unsafe_writes=true option.