LoginSignup
1
1

More than 3 years have passed since last update.

AWS EC2を毎月第2水曜日に自動的に再起動する

Posted at

毎月第2水曜日というのにてこずりました。

ゴール

EC2インスタンスを、毎月第2水曜、午前3時に停止、午前4時に開始します。

Lambda

LambdaでEC2の停止と開始を行います。OSの再起動だとAWS上は起動したままになるので、停止と開始を行います。

EC2停止

lambda_function.py
import boto3
region = 'ap-northeast-1'
instances = ['X-XXXXXXXX', 'X-XXXXXXXX'] 

def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name=region)
    ec2.stop_instances(InstanceIds=instances)
    print('stopped your instances: ' + str(instances))

EC2開始

lambda_function.py
import boto3
region = 'ap-northeast-1'
instances = ['X-XXXXXXXX', 'X-XXXXXXXX'] 

def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name=region)
    ec2.start_instances(InstanceIds=instances)
    print('start your instances: ' + str(instances))

CloudWatch

スケジュールのCron式を作成します。TUE#2 で第2火曜です。Cron式ってややこしいですが、AWSの画面で次のトリガーが表示されるので超便利です。

毎月第2水曜 午前3時(世界時間 火曜18時)

0 18 ? * TUE#2 *

毎月第2水曜 午前4時(世界時間 火曜19時)

0 19 ? * TUE#2 *

実験結果


CPUのモニタリングで、日本時間3時から4時まで点が消えているので停止しています。上手くいったようです。

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