Saturday, 25 March 2023

Automated deployments your application from github with webhook, nginx

- example for app example.com
- i assume you installed nginx

1. Add a repository webhook on Github

- Settings > Webhooks > Add webhook: add a webhook with settings:
+ Payload UR: https://example-app.com/hooks/example-webhook
+ Content type: application/json
+ Secret: your-secret-key
+ SSL verification: enabled
+ Which events would you like to trigger this webhook: Default option: "Just the push event."
+ Active — Uncheck this option. We will activate later after we create the endpoin

2. Install Webhook server to listen incoming request from Github

- install Webhook server

curl -LJO https://github.com/adnanh/webhook/releases/download/2.8.0/webhook-linux-amd64.tar.gz
tar -xzf webhook-linux-amd64.tar.gz
sudo systemctl stop webhook.service
sudo cp webhook-linux-amd64/webhook /usr/bin/
sudo systemctl start webhook.service
webhook --version
# must be version 2.8.0
# webhook will start default port 9000, location in /usr/bin
# cmd for webhook
which webhook -version
# url guide webhook
https://github.com/adnanh/webhook
# webhook version 2.6.9 not working

- create /var/www/hook.json in

# create hooks.json
nano hooks.json
 
# add content for hooks.json
[
{
"id": "example-webhook",
"execute-command": "/var/www/auto_deploy/autodeploy-example.sh",
"command-working-directory": "/var/www/example.com",
"trigger-rule":
{
"and":
[
{
"match":
{
"type": "payload-hmac-sha1",
"secret": "your-secret-key",
"parameter":
{
"source": "header",
"name": "X-Hub-Signature"
}
}
},
{
"match":
{
"type": "value",
"value": "refs/heads/master",
"parameter":
{
"source": "payload",
"name": "ref"
}
}
}
]
}
}
]
 
# refs/heads/master: master is your branch commit

- create /var/www/auto_deploy/autodeploy-example.sh

#!/bin/sh

# 1. Fetch the latest code from remote
git pull -f origin master

# 2. Install dependencies
yarn install

# 3. (Optional) Build step that compiles code, bundles assets, etc.
# yarn build

# 4. Restart application
pm2 restart [app-name]

- make it executable for autodeploy-example.sh

chmod +x autodeploy-example.sh

- start Webhook

# to run webhook
/path/to/webhook -hooks hooks.json -verbose
webhook -hooks hooks.json -verbose

3. Config nginx for webhook

- configure nginx that redirects all requests with destination https://example.com/hooks/..... to Webhook.  

# open file virtual host file: example.com
sudo nano /etc/nginx/sites-available/example.com
# add following code
# Webhook reverse proxy
location /hooks/ {
proxy_pass http://127.0.0.1:9000/hooks/;
}
# Check NGINX config
sudo nginx -t
# reload nginx
sudo systemctl restart nginx

* some errors can happen

- [webhook] error in exec: "...autodeploy-example.sh": permission denied

# reason forget set excutive
chmod +x
autodeploy-example.sh

Thank you.



No comments:

Post a Comment

Golang Advanced Interview Q&A