簡單的遠端部署 fabfile.py
Fabric 是一個 Python(2.5-2.7)庫和命令列工具,用於簡化 SSH 在應用程式部署或系統管理任務中的使用。它允許你通過命令列執行任意 Python 函式。
通過 pip install fabric
安裝結構
在根目錄中建立 fabfile.py
:
#myproject/fabfile.py
from fabric.api import *
@task
def dev():
# details of development server
env.user = # your ssh user
env.password = #your ssh password
env.hosts = # your ssh hosts (list instance, with comma-separated hosts)
env.key_filename = # pass to ssh key for github in your local keyfile
@task
def release():
# details of release server
env.user = # your ssh user
env.password = #your ssh password
env.hosts = # your ssh hosts (list instance, with comma-separated hosts)
env.key_filename = # pass to ssh key for github in your local keyfile
@task
def run():
with cd('path/to/your_project/'):
with prefix('source ../env/bin/activate'):
# activate venv, suppose it appear in one level higher
# pass commands one by one
run('git pull')
run('pip install -r requirements.txt')
run('python manage.py migrate --noinput')
run('python manage.py collectstatic --noinput')
run('touch reload.txt')
要執行該檔案,只需使用 fab
命令:
$ fab dev run # for release server, `fab release run`
注意:你無法為 github 配置 ssh 金鑰,只需手動鍵入登入名和密碼,而 fabfile 執行時,與金鑰相同。