Scheduled start and stop of EC2 instances on AWS (Credits to Sanket Raut)

Technologies we’ll use:

  • EC2 (your cloud server)
  • Lambda (compute service that lets you run code without worrying about servers)
  • Cloud-watch (monitoring service for AWS)
  • Finally IAM (Identity and Access Management, control security access)

STEP 1 – EC2

You’ll need to make sure you have fired up an EC2 instance and that it is running. It doesn’t matter what is on the instance as long as it turns on. In our example we have fired up a test instance. This is the part of the article that you’ll need to have some knowledge about creating and running EC2 instances. If you know Step 1 then you are going to love the rest.

STEP 2 – LAMBDA STOP EC2

Now we are going to go the the Lambda console and create two functions. One for stopping our test EC2 instance and one for starting it.

[1] To get to the Lambda console click on ‘Services’ in the top right hand corner of the AWS console and click ‘Lambda’ under the ‘Compute’ section.

1

Note: If this is your first time using Lambda in AWS you’ll see this Getting Started screen. Click ‘Get Started Now’.

2

2] Then click “Author from Scratch” to start your first function.

i) Your your function a name: “EC2InstanceStop”, a description: “EC2 Instance Stop” and for Runtime select “Python 2.7”.

ii) In role section= use existing role–> select name of IAM role that we are going to create further.

Here we have create (lambda-start-stop-ec2)role.Then go for create function.

Configure triggers

[3] we are going to set up the trigger.click on function and below is the add trigger option.

3

[4] In trigger Select “Cloud Watch Events” and then “Create a new rule”:

4

[5] You should name the Rule something easy to remember self explanatory like “lambda-stop-ec2”. You can give it a description if you wish: “Lambda stop EC2”.

[6] For the “Rule type” this can get a bit tricky. I selected “Schedule expression” and choose to use a CRON expression “cron(0 22 * * ? *)”. Since the times are in UTC I put the hour at 22 (10pm at night) which is 18EST (6pm Eastern Standard Time). Remember that I wanted the EC2 to shut off automatically at 6pm as our developers usually leave around 5:30 each day. Half an hour gave enough time for employees to shut down their computers. You can of course set this to a later time to accommodate your needs.

cron(0 22 * * ? *) shuts the EC2 instance down at 6pm EST every day.

(Make sure to change time from GMT to IST for cron job and cron must be six space specified)

5

[7] Enable the trigger at the bottom of the page and click next.

[8] Then in the Lambda function code section paste this in to stop your EC2 instance:

import boto3

region='<region>’

instances=[‘i-<inst-id-1>’,’i-<inst-id-2>’]

def lambda_handler(event, context):

ec2=boto3.client(‘ec2′,region_name='<region>’)

ec2.stop_instances(InstanceIds=instances)

print ‘stopped your instances: ‘+ str(instances)

[9] You’ll need to replace the Region (‘XX-XXXXX-X’) and instance IDs (‘X-XXXXXXXX’) to match the ones you want to stop from the EC2 console window in AWS. One thing to note is that if you region ID is “us-east-1a” leave off the last letter and only put in “us-east-1”.

[11] Select “Create a custom role” from IAM Role section

i)Go to IAM Tab—>Go to Role

ii)Select Aws services—>Lambda Then Next

iii)Give Permissions=AWSXRayDaemonWriteAccess and AWSLambdaBasicExecutionRole and Create one Inline policy and paste the below code in JSON Tab

{

“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”: “*”

}

]

}

iv) go to Next and Give role name lambda-start-stop-ec2 and create role.

10] Go to Lambda Ec2instancestop functions configuration section.

In below basic setting give time out 10 second and save.

11] Finally Save the code Click the “Test” button and your instance should have stopped!

STEP 3 – LAMBDA START EC2

I’ll go a little faster now that you have the Stop EC2 function running.

To create the Start EC2 function click on “Functions” on the left hand side menu and then click “Create function”.

  1. Click “Author from scratch”.
  2. For the function name use “EC2InstanceStart”, description use “EC2 Instance Start”, Runtime select “Python 2.7”
  3. Add the “CloudWatch Events” trigger and select “Create a new rule”. Name it “lambda-start-ec2”. Description: “Lambda Start EC2”
  4. For the CRON expression use “cron(30 12 ? * MON-FRI *)”, enable the trigger and click “Next”. This starts the EC2 instances Mon-Fri at 8:30EST / 12:30UTC.
  5. Go to EC2InstanceStart function and Paste below code in lambda_function.py

import boto3

region='<region>

instances=’i-<inst-id-1>’,’i-<inst-id-2>’

def lambda_handler(event, context):

ec2=boto3.client(‘ec2′,region_name='<region>’)

ec2.start_instances(InstanceIds=instances)

print ‘started your instances: ‘+ str(instances)

6. For “Role” select “Choose an existing role” and from the “Existing role” dropdown select “lambda-start-stop-ec2” that you created earlier.

  • For adding role go to functions configuration and go to basic setting edit select existing role “lambda-start-stop-ec2”
  • set the timeout to 10 seconds.

7 . Next click the “Code” tab so that we can test the function we have just created. Click the “Test” button and your instance should have started!

You now have the ability to stop and start your EC2 instances in AWS there by adding automation that leads to cost effectiveness improving your bottom line.

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s