Automatic directory synchronization between two nodes

Often you need to synchronize configuration files or an entire directory between two nodes. Moreover, it is advisable to do this continuously and unnoticeably. The best tool for this is, of course, rsync. However, it must be run manually after each file update. In this post I will use systemd units to do this automatically.


Obviously, we will need two servers, let's call them node1 and node2 in this case.

We need to set up a passwordless SSH connection between them for rsync to work. Check the connection and accept (yes) the connection to add the node to the known hosts file.

At the first stage, we will transfer selinux to permissive mode so that everything works.

Systemd .path unit file

Systemd can monitor files and directories and take action based on the results. I will use this feature to sync haproxy configuration files between two nodes.

The first module is the .path module, which defines the directories and files to monitor.

# cat /etc/systemd/system/haproxy-conf-sync.path
Description=Syncing config files



This unit file will start haproxy-conf-sync.service if the /etc/haproxy/haproxy.cfg file or the contents of the /etc/haproxy/certs directory are changed.

It is recommended to name the corresponding haproxy-conf-sync.service unit with the same name as .path unit, but with the .service suffix to simplify configuration housekeeping.

# cat /etc/systemd/system/haproxy-conf-sync.service
Description=Syncing haproxy config files

ExecStart=/usr/bin/rsync -avz -e '/usr/bin/ssh -i /root/.ssh/id_ed25519 -l root' /etc/haproxy/
ExecStartPost=/usr/bin/systemctl restart haproxy.service


Correct the IP address for your other node (pay attention to this when setting up the second node).

Once you have unit files, enable and start them

# systemctl daemon-reload 
# systemctl enable --now haproxy-conf-sync.service haproxy-conf-sync.path

Inspect logs for errors:

# journalctl -f -u haproxy-conf-sync.path -u haproxy-conf-sync.service

Selinux tuning

When the node is still in permissive mode, all actions are allowed and logged. Use auditing tools to obtain security events and create your custom selinux policy.

# grep AVC /var/log/audit/audit.log | audit2allow -M haproxy-conf-sync

The name after -M will be a name of your custom module.

Check the haproxy-conf-sync.te file to include only relevant actions. The previous command also creates a .pp file, but if you changed the .te file, you will have to create the .pp file again.

# semodule_package -o haproxy-conf-sync.pp -m haproxy-conf-sync.te

Apply your module and return to enforcement mode.

# semodule -i haproxy-conf-sync.pp
# setenforce 1

Updated on Thu May 16 11:18:44 IDT 2024 More documentations here