Connect VPN during CI/CD

I know this is an old thread, but it is google result #1 when looking for this topic so I’ll share my solution here.

before_script:
  ##
  ## VPN
  ## Inspiration from: https://torguard.net/knowledgebase.php?action=displayarticle&id=138
  ## And http://forum.gitlab.com/t/connect-vpn-during-ci-cd/7585
  ## Content from Variables to files: https://stackoverflow.com/a/49418265/4396362
  ## Waiting for opnevpn connect would be better than sleeping, the closest would be https://askubuntu.com/questions/28733/how-do-i-run-a-script-after-openvpn-has-connected-successfully
  ## Maybe this would work https://unix.stackexchange.com/questions/403202/create-bash-script-to-wait-and-then-run
  ##
  - which openvpn || (apt-get update -y -qq && apt-get install -y -qq openvpn) # Install openvpn if not available.
  - cat <<< $CLIENT_OVPN > /etc/openvpn/client.conf # Move vpn config from gitlab variable to config file.
  - cat <<< $VPN_U > /etc/openvpn/pass.txt # Move vpn user from gitlab variable to pass file.
  - cat <<< $VPN_P >> /etc/openvpn/pass.txt # Move vpn password from gitlab variable to pass file.
  - cat <<< "auth-user-pass /etc/openvpn/pass.txt" >> /etc/openvpn/client.conf # Tell vpn config to use password file.
  - cat <<< "log /etc/openvpn/client.log" >> /etc/openvpn/client.conf # Tell vpn config to use log file.
  - openvpn --config /etc/openvpn/client.conf --daemon # Start openvpn with config as a deamon.
  - sleep 30s # Wait for some time so the vpn can connect before doing anything else.
  - cat /etc/openvpn/client.log # Print the vpn log.
  - ping -c 1 <IP> # Ping the server I want to deploy to. If not available this stops the deployment process.

  ##
  ## SSH
  ## Inspiration for gitlab from https://docs.gitlab.com/ee/ci/ssh_keys/
  ## Inpsiration for new key from https://www.thomas-krenn.com/de/wiki/OpenSSH_Public_Key_Authentifizierung_unter_Ubuntu
  ##
  - which ssh-agent || (apt-get update -y -qq && apt-get install openssh-client -y -qq) # Install ssh-agent if not available.
  - eval $(ssh-agent -s) # Run ssh-agent.
  - mkdir -p ~/.ssh # Create ssh directory.
  - cat <<< $SSH_PRIVATE_KEY > ~/.ssh/id_rsa # Move ssh key from gitlab variable to file.
  - chmod 700 ~/.ssh/id_rsa  # Set permissions so only I am allowed to access my ssh key.
  - ssh-add # Add the key (no params -> default file name assumed).
  - cat <<< $SSH_KNOWN_HOSTS_DMS > ~/.ssh/known_hosts # Add the servers SSH Key to known_hosts prevent man in the middle attack.

When you add this before_script you are connected via VPN and you can simply use ssh and rsync as:
ssh username@ ‘command to execute’

I’m not completely happy with the sleep, but it was the easiest, yet reliable thing I could come up with.
If you have any suggestions for improvements let me know :slight_smile:

HTH

2 Likes