Select blank function in blueprint selection
Next without setting the trigger
Name:StopEC2 Description:stop EC2 Runtime: Python2.7
In the code of the Lambda function Described the code for stopping the instance.
python
import boto3
region = 'ap-northeast-1'
instances = ['X-XXXXXXXX']
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name=region)
ec2.stop_instances(InstanceIds=instances)
print 'stopped instances: ' + str(instances)
Set region and instances. The above specifies the Tokyo region (ap-northeast-1).
The explanation of Boto3 is as follows AWS SDK For Python (Boto3) https://aws.amazon.com/jp/sdk-for-python/
Choose to create a new role, Set the role name and policy.
The role name is lambda_start_stop_ec2. The policy allows you to start and stop EC2.
Policy document
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"ec2:StartInstances",
"ec2:StopInstances"
],
"Resource": "*"
}
]
}
Press Next.
After confirmation, press Create Function.
This completes the stop.
It is for starting, but basically the same as for stopping, Just change "ec2.stop_instances" in the function to "ec2.start_instances" and the rest is the same. Select the role you created earlier.
Select Event → Create Rule.
Select the schedule and cron expression to set the execution time. The time zone is UTC and cron is described below. https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/tutorial-scheduled-events-schedule-expressions.html
For the target, select StopEC2 of the Lambda function created earlier and perform "setting details".
Enter your name and description and you're done.
You can use the same description as stop except for the set time and changing the Lambda function to StartEC2.
You can check it in the log of the CloudWatch menu below.
that's all.
Recommended Posts