How do I use Lambda to stop and start Amazon EC2 instances based on tags at regular intervals?

How do I use Lambda to stop and start Amazon EC2 instances based on tags at regular intervals?


To use Lambda to stop and start EC2 instances at regular intervals, complete the following steps:

  1. Create a custom AWS Identity and Access Management (IAM) policy and IAM role for your Lambda function.
  2. Create Lambda functions that stop and start your EC2 instances.
  3. Test your Lambda functions.
  4. Create EventBridge schedules that run your function on a schedule.

Step 1: Create an IAM policy and IAM role for your Lambda function

Use the JSON policy editor to create an IAM policy. Paste the following JSON policy document into the policy editor:

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

    }

  ]

}        

Step 2: Create an IAM role for Lambda.

Important: When you attach a permissions policy to Lambda, make sure that you choose the IAM policy that you just created.

Create Lambda functions that stop and start your EC2 instances

1.  Open the Lambda console, and then choose Create function.

2.  Choose Author from scratch.

3.  Under Basic information, enter the following information:

For Function name, enter a name that identifies it as the function that's used to stop your EC2 instances. For example, "StopEC2Instances".

For Runtime, choose Python 3.9.

Under Permissions, expand Change default execution role.

Under Execution role, choose Use an existing role.

Under Existing role, choose the IAM role that you created.

4.  Choose Create function.

5.  On the Code tab, under Code source, paste the following code into the editor pane in the code editor on the lambda_function tab. This code stops the EC2 instances that you identify.

Example function code to stop EC2 instances

import bot
def stop_instances_by_tag(tag_key, tag_value, region):
    ec2 = boto3.client('ec2', region_name=region)
    # Retrieve instances based on tag
    response = ec2.describe_instances(Filters=[
        {'Name': 'tag:'+tag_key, 'Values': [tag_value]}
    ])
    instances = []
    # Extract instance IDs from the response
    for reservation in response['Reservations']:
        for instance in reservation['Instances']:
            instances.append(instance['InstanceId'])
    # Stop the instances
    if instances:
        ec2.stop_instances(InstanceIds=instances)
        print('Stopped instances: {}'.format(instances))
    else:
        print('No instances found with the specified tag.')
def lambda_handler(event, context):
    # Specify the tag key, value, and region
    tag_key = 'auto_instance_scheduler'
    tag_value = 'yes'
    region = 'ap-south-1'
    stop_instances_by_tag(tag_key, tag_value, region)o        

Important: Make sure to replace the tag_key, tag_value, and region variables with appropriate values that match your EC2 instances and requirements.

6. Choose Deploy.

7. On the Configuration tab, choose General configuration, and then choose Edit. Set Timeout to 10 seconds, and then choose Save.

Note: Configure the Lambda function settings as needed for your use case. For example, to stop and start multiple instances, you might use a different value for Timeout and Memory.

8. Repeat steps 1-7 to create another function. Complete the following steps differently so that this function starts your EC2 instances:

In step 3, enter a different Function name than the one that you used previously. For example, "StartEC2Instances".

In step 5, paste the following code into the editor pane in the code editor on the lambda_function tab.

import bot
def start_instances_by_tag(tag_key, tag_value, region):
    ec2 = boto3.client('ec2', region_name=region)
    # Retrieve instances based on tag
    response = ec2.describe_instances(Filters=[
        {'Name': 'tag:'+tag_key, 'Values': [tag_value]}
    ])
    instances = []
    # Extract instance IDs from the response
    for reservation in response['Reservations']:
        for instance in reservation['Instances']:
            instances.append(instance['InstanceId'])
    # Start the instances
    if instances:
        ec2.start_instances(InstanceIds=instances)
        print('Started instances: {}'.format(instances))
    else:
        print('No instances found with the specified tag.')
def lambda_handler(event, context):
    # Specify the tag key, value, and region
    tag_key = 'auto_instance_scheduler'
    tag_value = 'yes'
    region = 'ap-south-1'
    start_instances_by_tag(tag_key, tag_value, region)o        

Important: Make sure to replace the tag_key, tag_value, and region variables with appropriate values that match your EC2 instances and requirements.

Step 3: Test your Lambda functions

Open the Lambda console, and then choose Functions.

Choose one of the functions that you created.

Choose the Code tab.

In the Code source section, choose Test.

In the Configure test event dialog box, choose Create new test event.

Enter an Event name. Then, choose Create.

Note: Don't change the JSON code for the test event. The function doesn't use it.

7. Choose Test to run the function.

Repeat steps 1-7 for the other function that you created.

Check the status of your EC2 instances Using AWS Management Console You can check the status of your EC2 instances before and after testing to confirm that your functions work as you expect.

Step 4: Create EventBridge Rules to Schedule Your Lambda Functions

  1. Open the EventBridge console.
  2. Select "Create rule."
  3. Enter a Name and an optional Description for your rule, such as "StopEC2Instances."
  4. For Rule type, choose "Schedule," and then click "Continue in EventBridge Scheduler."
  5. Choose "Recurring schedule" for the Schedule pattern.
  6. Under Schedule pattern, select the Schedule type that suits your needs and configure the time interval accordingly.
  7. In the "Select targets" section, choose "Lambda function" from the Target dropdown list.
  8. For Function, choose the Lambda function that stops your EC2 instances.
  9. Click "Skip to review and create," then click "Create."

Repeat the above steps to create another rule to start your EC2 instances, with a different Name, Description, and the Lambda function that starts your instances.

That's it! You've set up Lambda functions to stop and start your EC2 instances and scheduled them to run at regular intervals using EventBridge rules.

.

.

.

.

#awslambda #amazonec2 #cloudcostsavings #automation #cloudcomputing #infrastructureascode #costoptimization #devops #serverless #cloudmanagement #AWSAutomation #CloudWatchEvents #boto3 #pythonscripting #AWSBestPractices


just minor error i've notice in the code you provided is import boto3 not bot and there is a random o at the ending of the last line, apart from that terrific job you saved me a lot of time!!

To view or add a comment, sign in

More articles by Manhar Dangar

Others also viewed

Explore content categories