Post

Gitea Deployment Automation with Webhook

Gitea Deployment Automation with Webhook

This document outlines the automated deployment process for Gitea repository using the adnanh/webhook service and a deployment script on Ubuntu.

Installation and Configuration:

adnanh/webhook can be install by running sudo apt-get install webhook which will install community packaged version in Ubuntu 17.04 or later.

Create a file named webhook.conf at /etc/webhook.conf with the following content:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
- id: zz-webhook-deploy-test
  execute-command: "/srv/example.com/www/gitea/deploy.sh"
  command-working-directory: "/srv/example.com/www/gitea"
  pass-environment-to-command:
    - source: "payload"
      name: "ref"
      envname: "REF"
    - source: "payload"
      name: "repository.name"
      envname: "REPOSITORY"
    - source: "payload"
      name: "repository.ssh_url"
      envname: "SSH_URL"
  include-command-output-in-response: true

This configuration defines a webhook named zz-webhook-deploy-test that triggers the deploy.sh script located at /srv/example.com/www/gitea when a push event occurs. The script receives the branch name and repository name as environment variables.

Now, run the command /usr/bin/webhook -nopanic -hooks /etc/webhook.conf -debug -verbose to expose the webhook in http://localhost:9000/hooks/zz-webhook-deploy-test.

Gitea Webhook Setup:

  • Go to your Gitea repository settings.
  • Under “Webhooks”, click “Add webhook.”
  • Enter the following details:
    • Target URL: http://localhost:9000/hooks/zz-webhook-deploy-test (replace with the actual server address if not running locally)
    • Trigger On: Select “Push events”
    • Active: Check the box
  • Click “Create webhook.”

Deploy Keys:

  • If the Gitea requires SSH authentication for pull requests, add a deploy key to the repository with appropriate permissions.

Deployment Script:

Create a file named deploy.sh at /srv/example.com/www/gitea with the following content:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/bin/bash

REPO=$REPOSITORY
# SSH_URL = ssh://gitea@localhost:2222/gitea/webhooks.git
REPO_SSH_URL=$SSH_URL

# Extract BRANCH_NAME from "/refs/heads/BRANCH_NAME"
ref=$REF
branch_name=${ref##*/}

# Do not continue script on errors
set -euo pipefail
set -x

echo Cleaning old deployment
rm -rf ${REPO}-${branch_name}

echo Cloning new commit from gitea $REPO branch $branch_name
git clone ${REPO_SSH_URL} \
  --branch "${branch_name}" --single-branch \
  --depth 1 \
  "${REPO}-${branch_name}"

echo Success
exit 0

This script extracts the branch name from the REF environment variable, cleans up any previous deployment directory for the specific branch, clones the repository from Gitea using the provided branch, and exits with a success message.

This post is licensed under CC BY 4.0 by the author.