webhook-setup-for-continuous-deployment

Webhook is utilized to listen for HTTP POST requests that trigger a preconfigured event, serving as a simple Continuous Deployment (CD) tool.

Installation

Install the webhook package using the following command:

apt install webhook

Configuration

Save the configuration in /etc/webhook.conf with the following content to create hook rules for incoming webhooks:

# Filename: /etc/webhook.conf
# Purpose: to create hook rules for the incoming webhook

- id: autodeploy
  execute-command: /srv/portal-dev.example.org/autodeploy.sh
  command-working-directory: /srv/portal-dev.example.org
  include-command-output-in-response: true
  include-command-output-in-response-on-error: true
  trigger-rule:
    and:
      - match:
          type: payload-hmac-sha1
          secret: <secret>
          parameter:
            source: header
            name: X-Hub-Signature
      - match:
          type: value
          value: refs/heads/main
          parameter:
            source: payload
            name: ref

Autodeploy Script

This script is triggered by the webhook to automate deployment processes:

#!/bin/bash

#!/bin/bash

# cmd triggered by webhook to run on /srv/app dir
set -e

# Change to the directory where your repository is and pull the latest changes
cd /srv/portal-dev.example.org/www
sudo git pull

# Run Laravel migrations inside the Docker container without interaction
docker exec -i -u root portal-dev.example.org /bin/bash -c "cd /var/www && php artisan migrate --force"

# Run composer install
docker exec -i -u root portal-dev.example.org /bin/bash -c "cd /var/www && ./composer install"

# Restart the container
docker-compose down
docker-compose up -d

Autostart on Reboot

Ensure webhook starts automatically after a reboot by creating a service file:

# /etc/systemd/system/webhook.service


[Unit]
Description=Small server for creating HTTP endpoints (hooks)
Documentation=https://github.com/adnanh/webhook/
ConditionPathExists=/etc/webhook.conf

[Service]
ExecStart=/usr/bin/webhook -nopanic -hooks /etc/webhook.conf -verbose

[Install]
WantedBy=multi-user.target

Start and enable the service using:

Proxy Pass Configuration for Traefik

Configure Traefik to proxy pass the webhook:

# Traefik v2.4.0 dynamic config fragment to expose the api dasbboard
# file: /opt/traefik/conf.d/00-deploy-app.yaml
http:
  routers:
    webhook:
      rule: "Host(`hooks.example.in`) && Path(`/hooks/autodeploy`)"
      entryPoints:
        - https
      service: deploy-app-service
      tls:
        certResolver: lets-encrypt

  services:
    deploy-app-service:
      loadBalancer:
        servers:
          - url: "http://172.17.0.1:9000"

Git Webhook URL

Configure the Git webhook to post to the following URL:

http://<ipaddress>:9000/hooks/autoredeploy
or
http://hooks.example.in/hooks/autoredeploy

Reference

For more information, visit the official webhook GitHub repository.