LoginSignup
7
13

More than 5 years have passed since last update.

fabricの雰囲気をつかむ

Last updated at Posted at 2015-10-09

fabricとは

Pythonでシェルスクリプトを実行できるツールです。環境設定やデプロイなど、何度も同じことを繰り返すときにfabricでまとめておくと便利になります。
操作される側はSSHさえ動いていれば使え、環境に依存しません。

ChefとかCapistranoでいいんじゃないの?

fabricはこの2つよりシンプルで覚えやすく、すぐ使えます。
既に習得済みの方は、乗り換えずにそのまま使えばいいと思います。

環境構築

ubuntu

sudo apt-get install fabric

centos

sudo yum install fabric

mac

brew install fabric

Windows

おとなしくLinuxを使いましょう。仮想環境なら構築は非常に簡単です。
Windows 7マシンで、VirtualBox+Vagrantを使いUbuntu 14.04を動かす

hello, world

fabricはカレントディレクトリに置いてある、fabfile.pyを実行します。

fabfile.py
# -*- coding: utf-8 -*

from fabric.api import *

def hello_world():
    local('echo "hello, world!') # local関数はfabricを実行している環境でシェルスクリプトを実行する

上記のようにファイルを作成し、下記のように「fab 関数名」をシェルで実行すると、fabfile.pyに記述した関数が実行されます。

fab hello_world

SSH経由で実行する

fabfile.py
# -*- coding: utf-8 -*

from fabric.api import *

def hello_world():
    run('echo "hello, world!') # run関数は指定したホストで実行する

localhostを指定していますが、適宜実行できる環境に書き換えてください。複数指定もできます。

fab hello_world -H localhost # -Hオプションで接続先を指定する

標準出力、終了コードを受け取る

デフォルトで終了コード0以外を受け取ると、その場で終了します。実行コマンドのオプションにwarn_onlyをつけると、終了せず警告を出力するだけになります。

fabfile.py
def hoge_exists():
    local('test -d /hoge')
    local('echo done') # ここまでこない
fabfile.py
def hoge_exists():
    with settings(warn_only=True):
        local('test -d /hoge')
        local('echo done') # doneと出力される

また、戻り値には標準出力の内容と終了コードが設定されています。

fabfile.py
# デコレータでもいい
@with_settings(warn_only=True)
def hoge_exists():
    # failedは終了コードが0以外ならTrue。succeededなら成功したか?
    if local('test -d /hoge').failed:
        local('echo なかったよ')
    else:
        local('echo あったよ')

    # quietをつけると何も表示しない
    with quiet():
        result = local('git config user.name', capture=True)
    local("echo %s" % result) # gitのユーザ名が表示されるはず

etc

なんとなく雰囲気はつかめたかと思います。

参考
Python製デプロイツール Fabricを初めて使う際に役立つTips

7
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
13