As mentioned in the question and the comments on it, this isn't an area in which Ansible excels. The "best" solution depends a bit on the type of file you're dealing with, and the structure of it.
The cleanest way to deal with these sorts of changes in Ansible is to templatize the entire thing; this allows you to see the entire file at once, rather than piecing it together through many places, and is much less fragile than pattern- or line-based approaches. When you need to add configuration in multiple places (for instance, different roles), that's when dynamic-loading directives become very useful, like Apache httpd's Include
:
Include /etc/httpd/conf.d/*.conf
This then allows you to write individual configuration files from different places, and let the client software concatenate them. However, as far as I can tell from a quick search, Tomcat doesn't support this, so you would need to operate with a single template file.
lineinfile
is a hacky solution that's very fragile, and template
is almost always a better option. However, in this case, the node that you're adding is a self-closing one, so as long as it is top-level, it can go anywhere and lineinfile
will work (I know you say it won't, but I'll get back to that). xml
is a similar option that's a bit less fragile.
Those two you've ruled out because they can't delete the comment you have in the file. However, I'll argue that that's an improper requirement (in most cases, and probably yours).
When using a configuration management tool, the source of truth shifts from the files themselves on servers to the configuration that's checked in to master. If someone wants to edit the file, they'll do so by editing the configuration management scripts, not by editing the file directly on the server. Therefore, there is no need for comments in the resultant file that lives on the server, except perhaps one at the top that says "this is auto-generated, go look at source control instead". The comment should be in your templating code - and as long as the result compiles and works correctly, you shouldn't care at all what it looks like.
conf.d
directory to which new files can be added easily.