webhook使用小记

项目地址:https://github.com/adnanh/webhook

看着是个阿三写的,一开始用有点不放心。后来看了star很多,索性试试呗。

webhook可以用来监听一个http事件,然后触发一些自定义操作(例如执行指定脚本)。引用一下,

webhook aims to do nothing more than it should do, and that is:

  1. receive the request,
  2. parse the headers, payload and query variables,
  3. check if the specified rules for the hook are satisfied,
  4. and finally, pass the specified arguments to the specified command via command line arguments or via environment variables.

Everything else is the responsibility of the command’s author.

目前没有单独的文档网站,就是仓库里的几个md文件。嘛~,毕竟用起来也不麻烦,应了它那句“只做自己该做的事”。下面是我的示例配置,

# /etc/webhook/hooks.yml
- id: test-webhook
  execute-command: /var/webhook/test.sh
  command-working-directory: /var/webhook
  trigger-rule:
    match:
      type: value
      value: refs/heads/master
      parameter:
        source: payload
        name: ref
 
- id: pull-git-repo
  execute-command: /var/webhook/pull-git-repo.sh
  # command-working-directory: /home/yychi/code/<repo>
  pass-environment-to-command:
    - source: string
      name: argumentvalue
    - source: payload
      name: repo
    - source: payload
      name: ref
    - source: header
      name: X-Webhook-Signature
    - source: payload
      name: sha
    - source: payload
      name: event_name
    - source: payload
      name: job
    - source: payload
      name: status
  trigger-rule:
    and:
      - match:
          type: payload-hmac-sha256
          secret: '{{ cat "/var/webhook/gh_webhook_secret" | js }}'
          parameter:
            source: header
            name: X-Webhook-Signature
      - match:
          type: regex
          regex: guyueshui/*
          parameter:
            source: payload
            name: repo

上面第一个是测试用,第二个是在github仓库action执行完后,获取通知,校验payload的sha256摘要,以及仓库地址符合正则表达式guyueshui/*。条件满足则执行脚本。另外,pass-environment-to-command用于看日志中接收的监听事件传的参数具体是啥,用于了解下其中原理,如果了然于胸,则可以去掉。

haproxy反向代理

webhooks默认运行于subpath /hooks 上,这对反代来说非常友好。贴一下haproxy的配置,

frontend  main
    bind :5000
    mode                 http
    log                  global
    option               httplog
    option               dontlognull
    option forwardfor    except 127.0.0.0/8
    maxconn              8000
    timeout              client  30s

    acl app-webhook      path           -i /hooks
    acl app-webhook      path_beg       -i /hooks/
    use_backend webhook        if app-webhook

backend webhook
    mode http
    option http-server-close
    option forwardfor
    http-request set-header Host %[req.hdr(host)]
    http-request set-header X-Real-IP %[src]
    http-request set-header X-Forwarded-For %[src]
    http-request set-header X-Forwarded-Proto %[hdr(X-Forwarded-Proto),lower]
    server  app1 127.0.0.1:9000 check maxconn 30