LoginSignup
3
2

More than 1 year has passed since last update.

boto3でEC2インスタンスサイズ変更(を自動化)

Last updated at Posted at 2019-06-15

概要

EC2のインスタンスサイズ変更をboto3で変更する方法です。
スクリプトをcronに登録しておけば、インスタンスサイズ変更を自動化できます。

環境

  • Amazon Linux
  • python 2.7.15
  • boto3 1.9.169

準備

  • boto3インストール
  • IAMロール作成
  • IAMロールを割り当てたIAMユーザ作成
  • IAMユーザの認証情報を実行端末のAWSプロファイルに設定済(本記事ではプロファイル名をEc2InstanceSizeChangeableUserとしてます)

参考情報

IAMロール例

Resourceに"*"(全て)を指定していますが、EC2のARNを指定することで操作可能なインスタンスを制限できます。

  • StartInstances インスタンスの開始
  • StopInstances インスタンスの停止
  • ModifyInstanceAttribute インスタンスサイズ変更
  • DescribeInstances/ReportInstanceStatus Wait処理
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ec2:StartInstances",
                "ec2:StopInstances"
            ],
            "Resource": "arn:aws:ec2:*:*:instance/*"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "ec2:ModifyInstanceAttribute",
                "ec2:DescribeInstances",
                "ec2:ReportInstanceStatus"
            ],
            "Resource": "*"
        }
    ]
}

スクリプト

modify_ec2_instance_size.py
import boto3
import sys
from boto3.session import Session

args = sys.argv

if len(args) <= 1:
    print('引数でインスタンスタイプを指定してください。例.t3.micro')
    sys.exit()

INSTANCE_ID = 'i-XXXXXXXXXXX'
NEW_INSTANCE_SIZE = args[1] # eg. t3.micro, t3.medium(2/4GB), t3.large(2/8GB)
PROFILE = 'Ec2InstanceSizeChangeUser'

print('instance id=[{}] instance type=[{}] profile=[{}]'.format(INSTANCE_ID, NEW_INSTANCE_SIZE,PROFILE))

session = Session(profile_name=PROFILE)
client = session.client('ec2')

# Stop the instance
print('stopping ...')
client.stop_instances(InstanceIds=[INSTANCE_ID])
waiter=client.get_waiter('instance_stopped')
waiter.wait(InstanceIds=[INSTANCE_ID])

# Change the instance type
print('changings...')
client.modify_instance_attribute(InstanceId=INSTANCE_ID, Attribute='instanceType', Value=NEW_INSTANCE_SIZE)

# Start the instance
print('staring...')
client.start_instances(InstanceIds=[INSTANCE_ID])
3
2
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
2