LoginSignup
9
8

More than 5 years have passed since last update.

Fabricを使ってみた

Posted at

Fabricとは何か

pythonの2.5~2.7で使うことができるライブラリで、アプリケーションのdeployや権限まわりの処理を行うときに使うコマンドラインツール。

Fabric is a Python (2.5-2.7) library and command-line tool for streamlining the use of SSH for application deployment or systems administration tasks.

参考) http://www.fabfile.org/

インストール方法

Macでpipでライブラリを管理している場合、

$ pip install fabric

でインストールできます。

使い方

今回は

  • sshログインして、ファイルを作る

ということをやってみます。

以下のようなファイルを作ります。

#coding: utf-8


from fabric.api import run
from fabric.api import env

env.hosts = ["100.0.0.0"] # sshログインするサーバーのIPアドレス
env.user = "test_user"   # sshログインするサーバーのuser名
env.password = "pass"    # sshログインするサーバーのパスワード

def deploy():
  run("touch fab.txt")

コマンドを実行

$ fab -f <ファイル名> <関数名>

で実行できます。
上記の例において、ファイル名をremote_touch.pyとすると、

$ fab -f remote_touch.py deploy

で実行できます。

オプションfがない場合は

Fatal error: Couldn't find any fabfiles!
Remember that -f can be used to specify fabfile path, and use -h for help.
Aborting.

というエラーが出ます。 これは「ファブファイルがないぞ!」と言われているわけです。

fabfileとは?

デフォルトでは、(Pythonのインポート機構にしたがって) fabfile と名付けられた fabfile/ もしくは fabfile.py を探します。

fabコマンドを使うには、対象ファイルをfabfile.pyとする必要があるわけですね。

任意のファイル名を使う場合は、

$ fab -f <ファイル名> <関数名>

ファイル名をfabfile.pyとする場合は

$ fab <関数名>

で実行できます。

参考

良いところ

複数サーバーにするのが楽

env.hostsの配列に、サーバーのIPアドレスを追加するだけでできます。

以下は同じユーザーで同じpasswordの場合のサンプルコードです。

#coding: utf-8


from fabric.api import run
from fabric.api import env

env.hosts = ["100.0.0.0", "100.0.0.1"] # sshログインするサーバーのIPアドレス
env.user = "test_user"   # sshログインするサーバーのuser名
env.password = "pass"    # sshログインするサーバーのパスワード

def deploy():
  run("touch fab.txt")

以下は異なるユーザーで異なるpasswordの場合のサンプルコードです。

#coding: utf-8


from fabric.api import run
from fabric.api import env

env.hosts = ["user1@100.0.0.0", "user2@100.0.0.1"]
env.passwords = {"user1@100.0.0.1": "password1",
                 "user2@100.0.0.1": "password2",}
def deploy():
  run("touch fab.txt")

というような感じです。楽ですね。

より詳しい使い方

http://qiita.com/narikei/items/99e77eb2ff4029f2157c
https://heartbeats.jp/hbblog/2015/07/pythonsshfabric13tips.html

9
8
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
9
8