How to automatically deploy flask app on github

Viewed 586

I am hosting a flask web app on my Raspberry Pi 4 using nginx and uwsgi. I want to be able to automatically redeploy (restart the app server) the server when a change is pushed to the GitHub repository. I thought I could get somewhere using this guide on GitHub webhooks. When running the flask app locally and testing with GitHub using ngrok, everything works just fine. The problem is when the app is actually deployed. I am able to process the request from GitHub but the actual shell script isn't executed by the server. I think the problem is that the server needs to run the shell script rather than the flask app, but I need help figuring out how to do that.

here's my code for the webhook handling:

def webhook():
    """ github webhook for automated deployment using github """
    sender = request.json['sender']['login']

    if sender == GITHUB_USERNAME:
        # if the request is from my github account, we want to deploy properly
        #TODO secure
        return deploy(200)
    else:
        # otherwise send a bad request response
        return deploy(400)

def deploy(status_code):
    if status_code == 200:
        # execute the deployment
        try:
            result = subprocess.check_output(['cd /home/pi/resume && ./deploy.sh'], shell=True)
            app.logger.info(result.decode('utf-8'))
        except subprocess.CalledProcessError as e:
            return make_response('An error occurred during deployment:\n{}'.format(e), 500)
        response = 'Successfully deployed!'
    else:
        response = 'There was an error with the request.'

    return make_response(response, status_code)

and here is the shell script:

#!/bin/bash
echo "Pulling from master..."
git pull origin master
echo "Successfully pulled from master!"
echo "Restarting server..."
echo "Restarting myapp.service..."
sudo systemctl restart myapp
echo "Successfully restarted myapp!"
echo "Restarting nginx.service..."
sudo systemctl restart nginx
echo "Successfully restarted nginx!"
0 Answers
Related