Start and Stop AWS EC2 Instance using Python Boto3

In this article we are going to perform Creating IAM Policy in AWS, Creating IAM Role and Attach Permission Policies, Start and Stop AWS EC2 Instance using Python Boto3 and Creating CloudWatch Events to start and Stop EC2 instances.

Step #1: Creating IAM Policy in AWS

We have to create IAM Policy and Role which contains execution permission to EC2 instance and cloudwatch which we have to attach to Lambda function.

To create IAM policy and Role Login to AWS Management console and search “iam” in search box.

login-aws-manament-console-and-search-iam_1

You will redirected to IAM dashboard, click on Policies at left side.

redict-iam-dashboard_2

Click on Create Policy

click on create policy 3 1

Select JSON and paste the below policy into it and click on Tags.

{
    "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": "*"
        }
    ]
}

Add tags if you want and Click on Review

add tag and click on review 5 1

Give Name and Description to IAM Policy and click on Create Policy.

Step #2: Creating IAM Role and Attach Permission Policies

Next We have to create role and attaching policy which we have created above to it.

To create role navigate to IAM and click on Roles on left side and click on Create Role.

click on create role 5 1

Select AWS service ,select Lambda and click on Permissions.

select lambda under aws services 6 2

Attach existing policy which created above and click on Tags.

attach policy to role 1

Give the tag.

add tags to role 8 1

Enter Role name and Role Description and click on Create Role.

click on create role 2

Step #3: Start and Stop AWS EC2 Instance using Python Boto3

Below are steps to Start and Stop AWS EC2 Instance using Python Boto3

Step #3.1: Lambda Function to Stop EC2 Instance

Next Search Lambda and click on Create function.

search lambda and click on create function 10 1

In Author from scratch section give function name, Select Runtime as Python 3.8.

select author from scratch function nane and runtime 3

Under Permissions section, select use an existing role, in existing role add role which we have create above and click on Create function .

select existing role in lambda function 4

Copy the below Python Lambda function code to stop EC2 Instance , change EC2 instance name and region according to your and click on deploy.

import boto3
region = 'ap-south-1'
instances = ['i-058c934ca37be80b2', 'i-0c6a8b96ce9383b91']
ec2 = boto3.client('ec2', region_name=region)

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

Testing Lambda function to Stop RDS Instance.

Click on Lambda function, Go to Test, click on Configure test Events.

configure test events 5

Then click on Test. Now if everything is configures properly, Now EC2 instances will stop.

Step #4: Creating CloudWatch Events to start and Stop EC2 instances

Click on cloudwatch, you will be navigated to CloudWatch Console, Under Events , click Rules, Click on Create Rule.

Here you option Event Pattern and Schedule, Click on Schedule you can use Fixed rate or cron Expression.

If we want to schedule using Cron Expression, schedule job using UTC Time and Add Target , Select Lambda function and Click on Configure Details.

If you want to stop EC2 instances from monday to friday in every week at 9 pm (UTC Time), below is cron expression

30 15 ? * MON-FRI *

Now EC2 instances will stop as per cron expression time.

cloudwatch rule to stop ec2 instance 6

Step #3.2: Lambda Function to Start RDS Instance

Use Same IAM Policies and Role.

Create a New Lambda function to start EC2 Instances and configure new test events, Below is Lambda function code to start EC2 Instances, change EC2 instances name and region according to your.

import boto3
region = 'ap-south-1'
instances = ['i-058c934ca37be90b5', 'i-0c6a8b96ce9383b51']
ec2 = boto3.client('ec2', region_name=region)

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

Next create same CloudWatch Events and Rule as shown above to start EC2 instances as per CloudWatch Rule.

Cloudwatch cron expression to start EC2 instances at 9 am monday to friday in every week (UTC Time).

30 3 ? * MON-FRI *

Conclusion:

We have covered Creating IAM Policy in AWS, Creating IAM Role and Attach Permission Policies, Start and Stop AWS EC2 Instance using Python Boto3 and Creating CloudWatch Events to start and Stop EC2 instances.

Related Articles:

How to Create IAM User in AWS Step by Step

How to Attach IAM Role to EC2 Instance using CLI

How to Create Ubuntu Instance in AWS [7 Steps]

How to Create Linux EC2 Instance in AWS

AWS Create EC2 Instance from Snapshot

How to connect to AWS EC2 Instance using MobaXTerm

How to Enable Password Authentication for AWS EC2

How to Connect EC2 Instance using Putty

How to Transfer files to AWS Instance using WinSCP [2 Steps]

Lambda Function to Start and Stop RDS Instance

How to Create AWS DocumentDB and Connect [3 steps]

How to Install MySQL 5.7 on Amazon Linux 2

How to Create Postgres Database in AWS and connect

Monitoring EC2 Instances using CloudWatch

About DevOps Hint

DevOps Hint Founded in 2020 Community Site where you can find about How to Guides, Articles and Troubleshooting Tips for DevOps, SRE, Sysadmins and Developers.

1 thought on “Start and Stop AWS EC2 Instance using Python Boto3”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link