I need to setup OpenVPN client to start automatically on a CentOS 7 server for one of our recent projects at work. I’m not well versed in VPN technology, but the majority of the time was spent on something that I didn’t expect.
I go the VPN configuration and all the necessary certificates from the client, installed OpenVPN and tried it out. It seemed to work just fine. But the setting it up to start automatically and without any human intervention took much longer than I though it would.
The first issue that I came across was the necessary input of username and password for the VPN connection to be established. The solution to that is simple (thanks to this comment):
- Create a new text file (for example, /etc/openvpn/auth) with the username being the first line of the file, and the password being the second. Don’t forget to limit the permissions to read-only by root.
- Add the following line to the VPN configuration file (assuming /etc/openvpn/client.conf): “auth-user-pass auth“. Here, the second “auth” is the name of the file, relative to the VPN configuration.
With that, the manual startup of the VPN (openvpn client.conf) was working.
Now, how do we start the service automatically? The old-school knowledge was suggesting “service openvpn start”. But that fails due to openvpn being an uknown service. Weird, right?
“rpm -ql openvpn” pointed to the direction of the systemd service (“systemctl start openvpn”). But that failed too. The name of the service was strangely looking too:
# rpm -ql openvpn | grep service
/usr/lib/systemd/system/openvpn@.service
A little (well, not that little after all) digging around, revealed something that I didn’t know. Systemd services can be started with different configuration files. In this case, you can run “systemctl start openvpn@foobar” to start the OpenVPN service using “foobar” configuration file, which should be in “/etc/openvpn/foobar.conf“.
What’s that config file and where do I get it from? Well, the OpenVPN configuration sent from our client had a “account@host.ovpn” file, which is exactly what’s needed. So, renaming “account@host.ovpn” to “client.conf” and moving it together with all the other certificate files into “/etc/openvpn” folder allowed me to do “systemctl start openvpn@client“. All you need now is to make the service start automatically at boot time and you are done.