LoginSignup
32
41

More than 5 years have passed since last update.

fabric 書き方Tips

Last updated at Posted at 2015-08-10

localで実行したい

fabfile.py
from fabric.api import local
def test:
  local("ls")
コマンドライン
$ fab test

どこかリモートサーバーにsshした状態で実行したい

fabfile.py
from fabric.api import run
def test:
  run("ls")
コマンドライン
$ fab -i ${key} -u ${user} -H ${host} test

実行コマンドから環境変数を渡して実行したい

fabfile.py
from fabric.api import local
def test(value="hello"):
  local('echo %s' % value)
コマンドライン
$ fab test
# hello

$ fab test:value=ok
# ok

cdした状態で実行したい

fabfile.py
from fabric.api import cd, lcd, run
def test(value="hello"):
  #localの場合
  with lcd("/var/tmp/"):
    local("pwd")

  #remoteの場合
  with cd("/var/www/"):
    run("pwd")
コマンドライン
$ fab -i ${key} -u ${user} -H ${host} test
# /var/tmp/
# /var/www/

ファイルを転送したい

fabfile.py
from fabric.api import cd, put, run
def test():
  # SFTP転送
  put("~/local.txt", "/tmp/remote.txt")

  # 確認
  with cd("/tmp"):
    run("ls")
コマンドライン
$ fab -i ${key} -u ${user} -H ${host} test
# remote.txt

処理の途中でスリープさせたい

fabfile.py
import time
from fabric.api import local
def test():
  # 処理1
  local('echo A')

  # 30秒待つ
  time.sleep(30)

  # 処理2
  local('echo B')

並列にパラレル実行させたい

パターン1(コードに@parallelを付ける)

fabfile.py
from fabric.api import parallel

@parallel
def test():
  # 処理
コマンドライン
$ fab -H "host1,host2,host3" test

パターン2(-Pオプションを付けて実行する)

コマンドライン
$ fab -P -H "host1,host2,host3" test
32
41
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
32
41