The issue is that on the next ansible run, ansible identifies that the dest file does not matches the src file and it would then copy the file and make the change based on the regex again.
I am sure that others had this issue, could you suggest how it could be solved?
Seed your random number generator with some non-changing value that’s unique to the target host. Then your server_id will be “random” relative to that of other hosts, but constant (idempotent) for that host from run to run.
With that, you should be able to do in a single template whatever you’re trying to do with the pair of copy and line_in_file tasks.
That’s going to be the same “random” number each time for any given host, but different for each host.
We had a similar randomization problem, where we wanted to schedule a cron job on all of our hosts, but wanted to spread them out over the work day between 7AM and 7PM. We ended up doing this:
It’s tempting to move the seeding and the random() calls themselves up into the body of the task, but putting it in vars, and making the second dependent on the first, guarantees an order of evaluation. Otherwise, as we found out the hard way, you can get some inexplicable inconsistencies that make your cron job schedules dance around!