LoginSignup
3
3

More than 5 years have passed since last update.

fabricで任意のインスタンスへデプロイする

Last updated at Posted at 2016-03-16

AWSのタグ名を取得して、任意のインスタンスへのみデプロイできるようにする。

fabricとは

コマンドライン 経由で 任意の Python 関数 を実行するツールです。

(低レベルライブラリの上に構築された)サブルーチンのライブラリで、SSH経由で 簡単に かつ Python風に シェルコマンドを実行します

チュートリアル
http://fabric-ja.readthedocs.org/en/latest/tutorial.html
Fabric実行モデル
https://fabric-ja.readthedocs.org/ja/latest/usage/execution.html

PrivateIPの取得

条件にマッチしたインスタンスのPrivateIPを取得して、
hostsにsetすることで指定のインスタンスへのデプロイが可能。

・起動中であるインスタンス
・Roles/Enviromentのタグに任意のものを指定

@task
def set_hosts(e,r):
    """ホスト一覧取得"""
    client = boto3.client('ec2', region_name=region)
    # 対象インスタンスリストの取得
    instances = client.describe_instances(Filters=[
                                    {'Name':'tag:Roles', 'Values':[r]},
                                    {'Name':'tag:Environment', 'Values':[e]},
                                    {'Name': 'instance-state-name', 'Values': ['running']}
                                    ])
    # プライベートIPをenvに入れる
    for i in instances["Reservations"]:
            env.hosts.append(i["Instances"][0]["PrivateIpAddress"])

実行

例えばvimを入れる処理を追加。

@task
def install_vim():
  sudo("yum -y install vim")

実行すれば、指定のインスタンスへvimがインストールされる。

・対象
起動中、Enviroment=dev/Roles=web

[ec2-user@ip-172-16-66-177 fabric]$  fab set_hosts:e=dev,r=web install_vim
[172.16.66.177] Executing task 'install_vim'
[172.16.66.177] sudo: yum -y install vim
[172.16.66.177] out: Loaded plugins: priorities, update-motd, upgrade-helper

まとめ

タグ名の指定をきちんとしておけば、開発環境のWeb全台へなどのデプロイが簡単できる。

3
3
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
3
3