前々からコンソールで作りたいと思っていたec2インスタンスの制御をboto3を使って作成してみました。
import sys
import boto3
ACCESS_KEY = 'アクセスキー'
SECRET_KEY = 'シークレットアクセスキー'
REGION_NAME = 'ap-northeast-1'
def get_ec2_client(region = REGION_NAME):
'''ec2クライアントの作成.'''
ec2 = boto3.session.Session(
aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY).client('ec2', region)
return ec2
def list_ec2_servers():
'''ec2インスタンス一覧表示.'''
ec2 = get_ec2_client()
instances = ec2.describe_instances()
instance_list = []
for reservations in instances['Reservations']:
for instance in reservations['Instances']:
tags = parse_keyvalue_sets(instance['Tags'])
state = instance['State']['Name']
print(instance['InstanceId'] + "\t" + tags['Name'] + "\t" + state)
def parse_keyvalue_sets(tags):
'''Tagsリストのパーサ.'''
result = {}
for tag in tags:
key = tag['Key']
val = tag['Value']
result[key] = val
return result
def shutdown_ec2_server(server):
'''インスタンスのストップ.'''
ec2 = get_ec2_client()
print('stop ... ' + server)
if (server == 'all'):
instances = ec2.describe_instances()
instance_list = []
for reservations in instances['Reservations']:
for instance in reservations['Instances']:
instance_list.append(instance['InstanceId'])
ec2.stop_instances(InstanceIds=instance_list)
else:
ec2.stop_instances(InstanceIds=[server])
def start_ec2_server(server):
'''インスタンスの起動.'''
print('start ... ' + server)
ec2 = get_ec2_client()
ec2.start_instances(InstanceIds=[server])
def parse_params():
'''コマンドライン引数の処理.'''
result = {}
args = sys.argv
if (len(args) < 2):
return False
action = ""
if (args[1] != ""):
action = args[1]
if (action == 'list' or action == 'up' or action == 'down'):
result['action'] = action
else:
print('エラー:実行できないアクションです')
return False
if ((action == 'up' or action == 'down') and len(args) < 3): print('エラー:引数が足りません') return False if (len(args) > 2):
result['target'] = args[2]
return result
def show_usege():
print('Usage:')
print('python server.py list : 設定されたキーで見れるサーバ一覧')
print('python server.py up [server] : サーバ起動')
print('python server.py down [server] : サーバ停止')
print('python server.py down all : 全サーバ停止')
pass
params = parse_params()
if (params == False):
show_usege()
exit()
if (params['action'] == 'list'):
list_ec2_servers()
elif (params['action'] == 'up'):
start_ec2_server(params['target'])
elif (params['action'] == 'down'):
shutdown_ec2_server(params['target'])
自分で使う用ということで、エラー処理などはちゃんと実装していませんが、、アクセスキーとシークレットアクセスキーを取得したものに変更すれば動作するようになると思います。