It is possible to set up a really easy and simple CD process in any Virtual Machine using your GitHub/Bitbucket/GitLab repository and a few lines of code. Let me show you how!
There is a lot of ways to do this, and there are a few SaaS that offers CD, even free and open sources tools like Jenkins, or if you are using some Cloud provider like Google Cloud Platform or AWS you have other alternatives like building and image and deploying directly.
In this case, I am going to teach you how to set up an easy way to continuous deploy your files into your virtual machine using webhooks and without depending on any 3rd party service.
Let’s think about the logic first. What do we want? We want to deploy/update the files we have been working locally and pushed to our repository. That means we want to have our VM with the last files from our repo.
Here we can think on the first step:
- Install Git in our VM
- Create some credentials in the VM and save into our Git provider (SSH Keys) [Click here to see how]
- Clone the repo into the correct folder in our VM
We are done with the very first step, now we have our VM linked to our Git repo. So by running “git pull” we are going to update it any time. But… we want a CD process and should be 100% automatic.
The next step is to make a way to pull the content each time we push to the repo. To do that we need to create two files (it could be just one, but this method is more secure). The first file would be a PHP file (this example is for WordPress but if you are running Ruby, Python or Node you can do the same).
That file is going to run a bash file (because or VM is running on Linux) and that bash file should have all the bash commands we want to run each time we push our changes to the repo.
You should put the PHP file in any public directory and the bash file in a private directory not accessible via GET.
Another thing is that you need to put the correct folder for the CD command. In the bash file, I included a gulp command to minify the css, you can include your own commands that you want to execute when you push into the repo and the VM get that new changes. It could be to trigger an email notification or whatever.
Finally, we need to go to our git provider, in my case is GitHub, access the repository that you are working on go to settings. In the settings, you need to create a new webhook, and putting the whole URL for the file that is going to run the bash file (the file you put in a public folder into your VM).