It will use Cloudwatch events and Lambda function.
-
Make sure you have an appropriate role that lambda function is going to assume. For example, I have a role named "lambda_ec2_onoff". Its policy is
{ "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*", "ec2:Describe*" ], "Resource": "*" } ] }
-
change directory to
<project_root>/scripts/StartStopEc2InstancesLambda
, use bash shell to runinstall_dependency.sh
andzip_lambda_expression.sh
. After running, one zipped file, containing necessary contents inside directoryStartStopEc2InstancesLambda
will be created in parent folder, namely<project_root>/scripts
bash ./zip_lambda_expression.sh
-
Go to Lambda service of region Ohio. Click "Create function" button.
-
fill form using
Name: start_stop_instances.
Runtime: python 3.6,
Role: choose an existing role
Existing role: lambda_ec2_onoff -
Upload zipped file created in step 2. Then click "Save" at right upper corner.
-
Go to CloudWatch services. In the left menu, click "Rules" under "Events", then click "Create rule"
-
Event Source click "Schedule" radio button, Cron expression
0 13,14 ? * MON-FRI *
, targets choose "Lambda function", function choose "start_stop_instances". Configure input to be "Constant (JSON text)". Copy content in file<project_root>/scripts/StartStopEc2InstancesLambda/instance_start_event_constant.json
to input box of "Constant (JSON text)". Then click "Configure detail".Explanation, this event will be invoked twice at GMT 13:00 and 14:00 in every work day. This rule is going to trigger execution of Lambda function start_stop_instances with event content in
instance_start_event_constant.json
. The event object is available as a parameter of interface functionlambda_handler(event, context)
. The content in event specifies that instance will only be started when Lambda function is invoked between 08:55am ~ 09:05am of America/New_York timezone.
-
Name rule to be "StartEc2RunningIBGateway", input desired description then click "Create rule".
-
Next, create cloud watch event rule "StopEc2RunningIBGateway" like what is done in step 6-8. Go to CloudWatch services. In the left menu, click "Rules" under "Events", then click "Create rule".
-
Event Source click "Schedule" radio button, Cron expression
0 21,22 ? * MON-FRI *
, targets choose "Lambda function", function choose "start_stop_instances". Configure input to be "Constant (JSON text)". Copy content in file<project_root>/scripts/StartStopEc2InstancesLambda/instance_stop_event_constant.json
to input box of "Constant (JSON text)". Then click "Configure detail". -
Name rule to be "StopEc2RunningIBGateway", input desired description then click "Create rule".