ansible.builtin.replace

Hello,

I would like to,

  1. copy a file (template)
  2. edit 2 lines based on regex

I actually did it using copy and replace.

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?

Thanks so much,

Meir

also, on of the regex is replaced by a random string

this is the code line from the template,

server_id = {{ 32000 | random }}

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.

Thanks, I did something similar, created the random outside of ansible and mapping it as a variable to the template.
Thanks so much

You can do that of course, but then you’ve got this outside dependency. You could keep it all inside Ansible like so:

server_id = {{ 32000 | random(seed=ansible_ssh_host_key_rsa_public) }}

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:

  • name: abc cron job
    cron:
    name: “abc cron job”
    day: “*”
    weekday: “1-5”
    minute: “{{ rng_minute }}”
    hour: “{{ rng_hour }}”
    job: “/usr/local/sbin/abc”
    state: “{{ abc_cron | default(‘present’) }}”
    vars:
    rng_minute: “{{ 59 | random(seed=ansible_ssh_host_key_rsa_public) }}”
    rng_hour: “{{ 19 | random(seed=(rng_minute ~ ansible_ssh_host_key_rsa_public), start=7) }}”

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!