• TechOps

    Need clarity?
    Chat with our experts now

    • Web Hosting SupportWeb Hosting Support
    • Helpdesk Support

      Skilled and professional 24/7 helpdesk support

    • Product Support

      Boost your product support with our expertise

    • Managed ServicesManaged Services
    • Server Management

      Don't let server issues slow you down. Let us manage them for you

    • Server Monitoring

      Safeguard your server health with our comprehensive monitoring solutions

    • Staff AugmentationStaff Augmentation
    • Hire an Admin

      Transform your business operations with our expert administrative support

    • Hire a Team

      Augment your workforce with highly skilled professional from our diverse talent pool

  • CloudOps

    Confused?
    Discuss with our sales team now.

    • Author ProfileAWS
      Well Architected Review
    • Author ProfileFinOps As a Service

      FinOps As a Service

    • Migrate

      Upgrade the journey: Migrate & Modernize seamlessly

    • Modernize

      Effortless CloudOps mastery for seamless cloud management

    • Optimize

      Efficient CloudOps: Boosting performance through optimization

    • Manage

      Simplify compliance complexities with our dedicated service

  • DevOps

    How Supportsages
    is creating an
    impact?

    View Casestudies
    • Author Profile24/7 DevOps As a Service

      Round-the-clock DevOps for uninterrupted efficiency

    • Author ProfileCI/CD Pipeline

      Automated CI/CD pipeline for seamless deployments

    • Author ProfileInfrastructure As a Code

      Crafting infrastructure with ingenious code

    • Author ProfileDevSecOps

      Integrated security in continuous DevOps practices

    • Author ProfileHire DevOps Engineers

      Level up your team with DevOps visionaries

    • Author ProfileConsulting Services

      Navigate success with expert DevOps consulting

  • SecOps

    Expert SecOps Services
    for any Scale

    • Author ProfileVAPT

      Vulnerability Assessment and Penetration Testing

    • Author ProfileSource Code Review

      Ensuring source code security and safe practices to reduce risks

    • Author ProfileSecurity Consultation

      On demand services for improving server security

    • Author ProfileSystem Hardening

      Reduced vulnerability and proactive protection

    • Author ProfileManaged SOC

      Monitors and maintains system security. Quick response on incidents

    • Author ProfileCompliance as a Service

      Regulatory compliance, reduced risk

  • Insights

    Explore our latest
    insights and resources

    Blog

    Explore our latest articles and insights

    Case Studies

    Read about our client success stories

  • Contact Us

  • About
  • Certifications
  • Life at Supportsages
  • Events
  • Contact
  • Careers
  • Blog

  • Dedicated Support Team
  • Quasi-dedicated Support Team
  • Hire a DevOps Engineer
  • Hire a Billing Support Staff
  • Per-ticket Support Plan
  • Managed Services

  • Microsoft Azure Expert
  • AWS Cloud Expert
  • Hire a developer
SS

SupportSages

Bites of wisdom @ work


Copyright © 2008 - 2026 SupportSages Pvt Ltd. All Rights Reserved.
Privacy PolicyLegal TermsData ProtectionCookie Policy

Automated Start/Stop of EC2 instances using Lambda and CloudWatch

Glenn Max

  • 8 min read
Automated Start/Stop of EC2 instances using Lambda and CloudWatch

Generating audio, please wait...

The following guide will go through the steps involved in setting up Lambda functions to start/stop EC2 instances and creating Cloudwatch rules to automate the process of starting or stopping of EC2 instances at a specific time period.

The whole process is broken into 3 parts and they are listed below.

  1. Setting up IAM roles for Lambda functions.
  2. Creating Lambda functions in Python.
  3. Creating a CloudWatch Rule to trigger the Lambda functions.

Setting up IAM roles for Lambda functions.

The IAM role to be configured can be applied to all the instances or restricted to a particular instance. The steps mentioned here are for setting up IAM roles which applies to a specific instance, to do that the ARN or Amazon Resource Name of that particular instance needs to be mentioned in IAM policy. The syntax of the ARN is given below, please refer to the link given below to find more details about it.
https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html

arn:partition:service:region:account-id:resource-id
arn:partition:service:region:account-id:resource-type/resource-id
arn:partition:service:region:account-id:resource-type:resource-id

The account-id, instance-id needs to be obtained to create the ARN for that particular instance. A sample is given below, for an instance with id i-12345678 in an account with Account ID 9876-5432-1098 will be like the one given below.

arn:aws:ec2:*:987654321098:instance/i-12345678

The instance ID can be obtained from the EC2 Management Console and the Account ID will be available from the Billing dashboard.

Instance ID

 

Once the instance ID and account ID is obtained ARN for the corresponding instance can be written and can proceed to create IAM policy and role for the Lambda functions.

From the Identity and Access Management Panel, select Create policy.

Identity and Access Management Panel

 

Select JSON to enter the policy in JSON format.

JSON

 

The IAM policy to be entered is given below.

{
"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": "arn:aws:ec2:*:<account_id>:instance/<instance_id>"
}
]
}

Change the <account_id> and <instance_id> with corresponding values.

And in order to have an IAM policy which applies to all the instance in the account, modify the policy code as below.

{
"Effect": "Allow",
"Action": [
"ec2:Start*",
"ec2:Stop*"
],
"Resource": "*"
}

The policy is added in JSON format and select Review policy to continue.

Review Policy

Add a name to the policy and description and select Create policy.

Review Policy 1

Now the IAM Policy is created, proceed to create a Role, and attaching this policy to the IAM role.

Instance Management

Select Roles from the left side menu to continue with creating IAM Role. Select Create role and select Lambda as a use case for this role.

IAM Role

Select Permissions to continue and attach the policy has been created earlier to this IAM role.

Permission Policies

Attach a tag to the role for identification purposes (optional).

Create Role

Select Review to continue.

Create Role

Select `Create role` and the IAM role is created.

IAM

Now the required IAM policy and role is created, proceed to create Lambda functions.

Creating Lambda functions.

From the AWS Lambda console create two functions to start and stop the instance. Select Create function to proceed.

Lambda Functions

Choose Author from scratch. Enter a function name and choose Python 3.6 as runtime.

Here a function for starting the instance is created, a corresponding function name is entered describing the purpose of this function.

Create function

Under Permissions, expand Choose or create an execution role. From  Execution role, choose Use an existing role and under Existing role, choose the IAM role which has been created earlier.

Execution Role

Select Create function to continue.

Start Instance

Enter the following code to the Lambda function to start the instance.

import boto3
region = '<Region>'
instances = ['<Instance-ID>']
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
ec2.start_instances(InstanceIds=instances)
print('started your instances: ' + str(instances))

Replace <Region> and <Instance-ID> to corresponding values.

Start Instance 1

Scroll down the page to tweak the timeout value. Select Edit and enter a suitable value, leave the rest of the values to default. The default timeout value will be 3 sec.

Start Instance 2

After doing this save the function.

Lambda function

 

Now proceed to create a second function to stop the instance.

Repeat all the steps mentioned above once again and replace the function code with the one given below. Also, make sure to change the function name to a suitable one.

import boto3
region = '<Region>'
instances = ['<Instance-ID>']
ec2 = boto3.client('ec2', region_name=region)

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

Replace <Region> and <Instance-ID> to corresponding values.
Now Lambda function for starting and stopping the instance is created, proceed to create CloudWatch rule to trigger these Lambda functions.

Creating a CloudWatch Rule to trigger the Lambda functions.

Access the CloudWatch dashboard and from the left navigation pane, under Events, choose Rules.

Cloud Watch

Select Create rule.

Cloud Watch Events

Under Event Source, choose Schedule.

Event source

Choose Cron expression. Please note that all scheduled events use the UTC time zone, so convert the time period to UTC format and set the cron accordingly.

create rule

 

Select Targets and choose Lambda from the list.

cloud watch

Select the required Lambda function from one of the two functions created earlier. This CloudWatch rule will stop the instance at specificied time.

cloud watch 5

Select Configure details to continue.

cloud watch 6

Select Create rule and the CloudWatch rule for stoping instance is created. Set up another CloudWatch rule for starting the instance by repeating the steps performed earlier, only changes will be the time period of cron and the Lambda function.

cloud watch start 1

cloudwatch start2

Select Create rule and the CloudWatch rule for stating the instance is created.

cloudwatch complete

 

The CloudWatch will trigger these rules thereby invoking the Lambda function automating the start and stop of EC2 instance at a specific time period defined in CloudWatch event rule.

  • Linux

Looking for AWS Experts?

We provide top-of-the-line custom AWS setup services tailored to your needs.

Automated Start/Stop of EC2 instances using Lambda and CloudWatch

Adding DMARC record in cPanel/WHM

Adding DMARC record in cPanel/WHM
  • cPanel
logo

Creating an AWS instance

Creating an AWS instance
  • Sever management
logo

Socks5 proxy server setup with 3proxy

Socks5 proxy server setup with 3proxy
  • Linux
  • server
logo
Posts by Glenn Max

Glenn Max