• DevOps
    Case Study

    How we built a resilient multi-account, multi-cloud solution for a Health Tech service provider!

    READ CASESTUDY
    icon

    24/7 DevOps as a Service

    Round-the-clock DevOps for uninterrupted efficiency.

    icon

    Infrastructure as a Code

    Crafting infrastructure with ingenious code.

    icon

    CI/CD Pipeline

    Automated CI/CD pipeline for seamless deployments.

    icon

    DevSecOps

    Integrated security in continuous DevOps practices.

    icon

    Hire DevOps Engineers

    Level up your team with DevOps visionaries.

    icon

    Consulting Services

    Navigate success with expert DevOps consulting.

  • TechOps
    Case Study

    How we built a scalable Odoo solution for a Travel Tech service provider!

    READ CASESTUDY

    WEB HOSTING SUPPORT

    icon

    HelpDesk Support

    Highly skilled 24/7 HelpDesk Support

    icon

    Product Support

    Boost your product support with our expertise.

    MANAGED SERVICES

    icon

    Server Management

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

    icon

    Server Monitoring

    Safeguard your server health with our comprehensive monitoring solutions.

    STAFF AUGMENTATION

    icon

    Hire an Admin

    Transform your business operations with our expert administrative support.

    icon

    Hire a Team

    Augment your workforce with highly skilled professionals from our diverse talent pool.

  • CloudOps
    Case Study

    How we helped a Private Deemed University in India, save US $3500/m on hosting charges!

    READ CASESTUDY
    icon

    AWS Well Architected Review

    Round-the-clock for uninterrupted efficiency

    icon

    Optimize

    Efficient CloudOps mastery for seamless cloud management

    icon

    Manage

    Automated CI/CD pipeline for seamless deployments

    icon

    Migrate

    Upgrade the journey, Migrate & Modernize seamlessly

    icon

    Modernize

    Simplify compliance complexities with our dedicated services

    icon

    FinOps as a Service

    FinOps as a Service

  • SecOps
    Case Study

    How we built a scalable Odoo solution for TravelTech service provider!

    READ CASESTUDY
    icon

    VAPT

    Vulnerability Assessment and Penetration Testing

    icon

    Source Code Review

    Ensuring source code security ans safe practices to reduce risks

    icon

    Security Consultation

    On demand services for improving server security

    icon

    System Hardening

    Reduced vulnerability and proactive protection

    icon

    Managed SoC

    Monitors and maintains system security. Quick response on incidents.

    icon

    Compliance as a Service

    Regulatory compliance, reduced risk

  • Insights
    Case Study

    How we helped a Private Deemed University in India, save US $3,500/m on hosting charges!

    READ CASESTUDY
    icon

    Blog

    Explore our latest articles and insights

    icon

    Case Studies

    Read about our client success stories

    icon

    Flipbook

    Explore our latest Flipbook

    icon

    Events

    Join us at upcoming events and conferences

    icon

    Webinars

    Watch our educational webinar series

  • Our Story
  • Contact Us

Interested to collaborate?

Get in touch with us!

Ready to elevate your business with certified cloud expertise? Contact us today to learn how our team can help you leverage cloud technology to drive growth, streamline operations, and enhance security.

  • AWSAWS
  • Azure CloudAzure Cloud
  • Google CloudGoogle Cloud
  • Akamai CloudAkamai Cloud
  • OVHOVH
  • Digital OceanDigital Ocean
  • HetznerHetzner
  • Kubernetes Consultancy Services
  • K8s & Cloud native Solutions
  • 24/7 Infrastructure Monitoring
  • DevOps as a Service
  • Cloud CI/CD Solutions
  • White Labeled MSP Support
  • Our story
  • Life@SupportSages
  • Insights
  • Careers
  • Events
  • Contact Us

Connect with us!


LinkedInFacebookXInstagramYouTube

aws partneraws advanced partner
SupportSages

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

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
Automated Start/Stop of EC2 instances using Lambda and CloudWatch

Posts by Glenn Max

Glenn Max