Amazon Web ServiceをAPIライブラリbotoで操作する(EC2編 その2)

このエントリーをはてなブックマークに追加
こんにちは、シャノンのYanaです。
関東地方も大雪と大騒ぎでしたが、思った以上に積もらずホッとしています。
雪が嫌いなわけではなく凍った道が怖いだけです。

今回も、前回に引き続きBoto(PythonのAWS API ライブラリ)です。
途中だったInstanceの起動、停止、ImageからInstanceを起動を共有させていただきます。

Boto公式サイトはこちら

1.ImageからInstanceの起動する


ImageからInstanceを起動する際に最少の情報で下記が必要になります。
  1. ImageのID
  2. InstanceにアクセスするためのKey(Key Pairsから)
  3. Securityルール(Security Groupsから)
  4. Instanceタイプ(t1.micro, m1.largeなど)
  5. Instanceの起動数
imageからIncetanceを起動するためには、
imageオブジェクトのrunを利用します。
images[0].run()
※引数はサンプルを参考にしてください。
run_image(asia_conn,options.image_id)

def run_image(conn,image_id):
    images = conn.get_all_images(image_ids=[image_id])
    security_group = conn.get_all_security_groups(groupnames='test-security-policy')
    rsv = images[0].run(min_count=1,max_count=1,key_name='test_key1',security_groups=[security_group[0]],instance_type='t1.micro')
    ins = rsv.instances
    print ('Running instance : %s' % ins)
    wait_status(ins[0], 'running')

#起動には一定の時間が必要なため(t1.microならば数十秒ほど)、完了するまでWaitするようにしています。
def wait_status(ins, status):
    while True:
        ins.update()
        if(ins.state == status):
            print ('Status: %s'% ins.state)
            return 1
        time.sleep(5.0)

def conn_asia_region_ec2(conn):
    region = conn.get_all_regions()
    asia_conn = region[3].connect(aws_access_key_id=AWS_ACCESS_KEY ,aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
    return asia_conn

これでインスタンスが起動し利用可能となります。

2.Instanceを起動する、停止する

インスタンス操作に最低限必要なのは、
  1. リージョンへのコネクション
  2. InstanceID
の2つです。
リージョンへのコネクションオブジェクトを利用して
start_instancesとstop_instancesで操作します。

def start_instance(conn, start_instance_id):
    ins = conn.start_instances(instance_ids=[start_instance_id])
        print('Start instance : %s' % ins)
        wait_status(ins[0], 'running')
        infomation_instance(conn,start_instance_id)

def stop_instance(conn, stop_instance_id):
    ins = conn.stop_instances(instance_ids=[stop_instance_id])
        print('Stop instance : %s' % ins)
        wait_status(ins[0], 'stopped')
起動実行後は、Imageからの起動と同様にステータスが変わるまでWaitします。

3.Image(AMI)の作成


稼動しているInstanceからImageを作成します。
必要最低限で必要なのは、
  1. instanceID
  2. ImageName
ですが、用途の説明にdescriptionも残すことをお勧めします。
サンプルでは、Nameには日付、Descriptionには元のInstanceIDを指定しています。

def create_image(conn,ins_id):
    name = time.strftime('%Y%m%d-%H-%M')
    desc = ('from %s instances' % ins_id)
    conn.create_image(instance_id=ins_id, name=name , description=desc)
    print('complate create image')

EC2限定の操作方法でしたが、Botoの便利さがお伝えできれば幸いです。
サーバの起動から停止など、他の操作をトリガーに自動でEC2を利用するためにBotoを利用しました。

次回は、AWSやBotoを利用して構築した、弊社QA部の自動化テスト環境の仕組みについてご紹介させていていただきます。
次の記事
« Prev Post
前の記事
Next Post »
Related Posts Plugin for WordPress, Blogger...