EC2 定時自動開關機

EC2 定時自動開關機

EC2 (虛擬主機) 是按時間計費的,如果它非24小時提供服務,我們則可以把它設置為上班開起、下班關閉,這樣一來就可以減少成本囉!

使用 Lamdba,需要先為它設置一個 role,讓它有權限對ec2 開啟Start / 關閉Stop

登入 AWS console > IAM > Role > 【create role】
下面是 policy 的 Json,並套用到 new role

{ 
"Version": "2012-10-17",
"Statement":
[
{
"Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ],
"Resource": "arn:aws:logs:*:*:*" },
{
"Effect": "Allow", "Action": [ "ec2:Start*", "ec2:Stop*" ], "Resource": "*"
}
]
}

Python code for Start instance

import boto3
# Enter the region your instances are in. Include only the region without specifying Availability Zone; e.g.; ‘us-east-1’
region = ‘XX-XXXXX-X’
# Enter your instances here: ex. [‘X-XXXXXXXX’, ‘X-XXXXXXXX’]
instances = [‘X-XXXXXXXX’]

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

Python code for Stop instance

import boto3
# Enter the region your instances are in. Include only the region without specifying Availability Zone; e.g., ‘us-east-1’
region = ‘XX-XXXXX-X’
# Enter your instances here: ex. [‘X-XXXXXXXX’, ‘X-XXXXXXXX’]
instances = [‘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)

在CloudWatch新增兩筆 rule –> StartEC2 / StopEC2

Cloudwatch event setup for cron schedule
cloudwatch的時間排程設置,是UTC:而台灣時間 -8,就是UTC現在的時間,譬如台灣15點,減8 = 7點就是UTC的時間

點擊查詢現在的UTC時間

台灣的上午8點,UTC為:
0 0 ? * MON-FRI *

台灣的下午5點,UTC為:
0 9 ? * MON-FRI *

Cron Expressions 格式

下面這兩段影片,更清楚要怎麼設置,請享用~

發佈留言