How can I make strongSwan clients auto reconnect when server is down?

I would like clients to try reconnecting indefinitely if server is down so when it comes back, the client simply reconnects.

Client ipsec.conf

conn %default
    ike=aes256gcm16-sha384-modp3072!
    esp=aes256gcm16-sha384-modp3072!

conn ikev2
    auto=start
    [email protected]
    leftsourceip=%config
    leftauth=eap-tls
    leftcert=vpn-client.crt
    right=my-vpn.com
    rightid=my-vpn.com
    rightsubnet=0.0.0.0/0
    rightauth=pubkey

You'd usually use trap policies, so traffic matching the IPsec policies installed in the kernel automatically trigger the negotiation of IKE and IPsec SAs. They also prevent any matching traffic from leaving the host unencrypted. However, to make this work with virtual IPs (leftsourceip) this requires a relatively recent version of strongSwan (5.6.3 or newer to be precise).

So with newer releases, or in scenarios that don't use virtual IPs, just configure auto=route. And don't set any of the settings mentioned below (or set them to clear, keyingtries may be set to 1).

When using virtual IPs with an older release, you may configure dpdaction=restart, closeaction=restart and keyingtries=%forever (together with auto=start) to recreate the SAs if they get terminated by the peer or due to network problems (unencrypted traffic may leave the host while this happens, unless you prevent that via firewall). As mentioned above, you shouldn't use these settings when using trap policies as that might cause additional IPsec SAs (triggered by traffic hitting these policies while SAs are concurrently already being recreated). Also note that there are some fatal errors (e.g. authentication failures) that currently don't trigger the recreation of the affected IKE SA, so this may require a script that occasionally checks if the SAs are there or being established (using the error-notify plugin as trigger could also be an option).