3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Boto3で特定のタグが付与されたインスタンスを停止する

Last updated at Posted at 2017-05-31

以前作成した特定のインスタンスをBoto3でstop処理をパワーアップさせてみました。

前提として
EC2にenvタグを付与しておき値はdevとして設定したインスタンスを仕込んでおきます。

Filtersの処理が上手く出来なかったですが、なんとか出来ました。
記念にブログアップ。次はLambdaと連携してみる。

# -*- coding: utf-8 -*-

# import
import boto3
from boto3.session import Session

ec2 = boto3.client('ec2')
dev_list = []

# def
def get_list():
  instance_list = ec2.describe_instances(
    Filters=[{'Name': 'tag:env', 'Values': ['dev']}]
  )
  for Reservations in instance_list['Reservations']:
    for dev_instances in Reservations['Instances']:
      dev_list.append(dev_instances["InstanceId"])
      return dev_list

def ec2_stop(dev_list):
  for instance_id in dev_list:
    response = ec2.stop_instances(
      InstanceIds=[
        instance_id
      ]
    )

# Main
if __name__ == "__main__":
  get_list()
  ec2_stop(dev_list)

3
4
2

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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?