文章來源:王琦的個人博客-使用OpenResty和Lua實現git pull ,互聯網打雜,喜歡多語言編程,記錄一些知識碎片,分享一些心得。
本章介紹如何安裝openresty,以及寫一個簡單的Lua配合github的webhook 來實現自動更新博客。
安裝openresty
**注意:**屏蔽了安裝時指定user 爲www,因爲在測試過程中,nginx用戶爲www會導致腳本執行git pull出現Host key verification failed。無法正常拉去代碼,解決辦法就是在nginx.conf裏指定user 爲rootuser root
。
# 安裝依賴庫
yum install pcre-devel openssl-devel gcc curl zlib-devel readline readline-devel\
readline-devel libxslt-devel gd-devel \
libevent libevent-devel
# 準備工作
useradd www -s /sbin/nologin -M
mkdir -p /soft/package/src
cd /soft/package/src
# 更新至最新版本
wget https://openresty.org/download/openresty-1.15.8.1.tar.gz
tar xf openresty-1.15.8.1.tar.gz
cd openresty-1.15.8.1
# 編譯安裝LuaJIT
cd bundle/LuaJIT-2.1-20161104/
make clean && make && make install
# 創建軟件路徑
mkdir -p /soft/openresty-1.15
# 安裝openresty 可根據自己需要啓用模塊
./configure \
#--user=www \
#--group=www \
--prefix=/soft/openresty-1.15 \
--http-proxy-temp-path=/soft/openresty-1.15/nginx/proxy_temp \
--http-fastcgi-temp-path=/soft/openresty-1.15/nginx/fastcgi_temp \
--with-http_ssl_module \
--with-threads \
--with-file-aio \
--with-http_ssl_module \
--with-http_iconv_module \
--with-http_realip_module \
--with-http_gzip_static_module \
--with-http_secure_link_module \
--with-http_stub_status_module \
--with-http_auth_request_module \
--with-http_random_index_module \
--with-http_image_filter_module
gmake && gmake install
# 建立軟鏈
ln -s /soft/openresty-1.15 /soft/openresty
ln -s /soft/openresty-1.15/nginx/sbin/nginx /usr/bin/nginx
# 啓動nginx
nginx
# 修改配置文件 測試下lua
vim /soft/openresty/nginx/conf/nginx.conf
location /test {
default_type 'text/html';
content_by_lua 'ngx.say("hello world")';
}
# 重載配置
nginx -s reload
# 訪問127.0.0.1/test 可以看到輸出
hello world
編寫腳本
1、先寫一個shell腳本,用於執行git pull。
#git_pull.sh
#! /bin/bash
dir=/www/hiwangqi
git=/usr/bin/git
cd $dir
$git pull origin master
if [ $? -eq 0 ]; then
date=`/usr/bin/date +%F' '%T`
echo "ok $date" >> /www/hiwangqi/gitlog.txt
fi
2、接下來要編寫Lua腳本,有更多需求可以去查閱github關於webhooks的文檔。 傳送門
--web_hook.lua
local sign = ngx.req.get_headers()['X-Hub-Signature']
local secret = 'woshini88'
if sign == nil then
return ngx.say("You do not have permission to get URL from this server.")
end
local arr = {}
for k,v in string.gmatch(sign,"(%w+)=(%w+)") do
arr[k]=v
end
ngx.req.read_body()
local str = require "resty.string"
local data = ngx.req.get_body_data()
if data == nil then
return ngx.say("You do not have permission to get URL from this server.")
end
local des = ngx.hmac_sha1(secret, data)
if not str.to_hex(des) == arr["sha1"] then
return ngx.exit(404)
end
local shell = require "resty.shell"
local stdin = ""
local timeout = 5000 -- ms
local max_size = 8096 -- byte
local ok, stdout, stderr, reason, status = shell.run("bash /server/scripts/git_pull.sh",stdin,timeout,max_size)
if not ok then
ngx.say(stdout)
ngx.say(stderr)
ngx.say(status)
end
ngx.exit(200)
3、設置nginx配置文件
location /web_hook
{
default_type 'text/html';
#content_by_lua 'ngx.say("hello world")';
content_by_lua_file /server/scripts/web_hook.lua;
}