Continuous Delivery - kgolezardi/SAD-Project GitHub Wiki

Suppose we already have a virtualenv for webhook with gunicorn and flask installed.

Setting Up a Flask Application

First, we create the webhook application ~/deploy_webhook/webhook.py:

import os
from flask import Flask, request
app = Flask(__name__)

@app.route("/")
def deploy():
    os.system("git --git-dir=/home/bidilo/SAD-Project/.git --work-tree=/home/bidilo/SAD-Project pull origin master")
    os.system("rm -rf /home/bidilo/SAD-Project/bidilo/staticfiles")
    os.system("/home/bidilo/bidiloenv/bin/python /home/bidilo/SAD-Project/bidilo/manage.py collectstatic")
    os.system("/home/bidilo/bidiloenv/bin/python /home/bidilo/SAD-Project/bidilo/manage.py migrate")
    os.system("/home/bidilo/bidiloenv/bin/pip install -r /home/bidilo/SAD-Project/bidilo/requirements/production.txt")
    os.system("sudo systemctl restart gunicorn")
    return '', 200

if __name__ == "__main__":
    app.run(host='0.0.0.0')

Creating the WSGI Entry Point

$ vim ~/deploy_webhook/wsgi.py:

from webhook import app

if __name__ == "__main__":
    app.run()

In order for the sudo systemctl command work without asking for password, you should add the line bidilo ALL=(ALL) NOPASSWD: ALL at the end of the file showing by the command sudo visudo.

Configuring Gunicorn

You can bind Gunicorn manually for testing, but we skip it for now.

$ sudo vim /etc/systemd/system/bidilo-webhook.service:

[Unit]
Description=Gunicorn instance to serve bidilo webhook
After=network.target

[Service]
User=bidilo
Group=www-data
WorkingDirectory=/home/bidilo/deploy_webhook
Environment="PATH=/home/bidilo/deploy_webhook/vevn/bin"
ExecStart=/home/bidilo/deploy_webhook/vevn/bin/gunicorn --workers 3 --bind unix:bidilo-webhook.sock -m 007 wsgi:app

[Install]
WantedBy=multi-user.target

This starts and enables the service:

$ sudo systemctl start bidilo-webhook
$ sudo systemctl enable bidilo-webhook

Configuring Nginx to Proxy Requests

$ sudo vim /etc/nginx/sites-available/bidilo-webhook

server {
    listen 5001;
    server_name IP;

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/bidilo/deploy_webhook/bidilo-webhook.sock;
    }
}

Then we do these final things...:

$ sudo ln -s /etc/nginx/sites-available/bidilo-webhook /etc/nginx/sites-enabled
$ sudo ufw allow 5001
$ sudo systemctl restart nginx

Don't forget to create the push webhook in GitHub repo settings pages.

This document has been came to life by the help of this page.