HOw to schedule Lambda script to perform periodic EC2 tasks

I have an ask at work to terminate EC2 instances that have been stopped for 30 days. I have a python boto3 script:

import boto3
import re
from datetime import datetime

TERMINATION_AGE = 30

ec2_client = boto3.client(‘ec2’, region_name=‘ap-southeast-2’)

Get a list of stopped instances

instances = ec2_client.describe_instances(Filters=[{‘Name’: ‘instance-state-name’, ‘Values’: [‘stopped’]}])

for reservation in instances[‘Reservations’]:
for instance in reservation[‘Instances’]:

    # StateTransitionReason might be like "i-xxxxxxxx User initiated (2016-05-23 17:27:19 GMT)"
    reason = instance['StateTransitionReason']
    date_string = re.search('User initiated \(([\d-]*)', reason).group(1)
    if len(date_string) == 10:
        date = datetime.strptime(date_string, '%Y-%m-%d')

        # Terminate if older than TERMINATION_AGE
        if (datetime.today() - date).days > TERMINATION_AGE:
            ec2_client.terminate_instances

My question is,

  1. How can I use this script to put it into action using Lambda?
  2. How can I trigger lambda to run this script every 30 days?

You can use EventBridge schedule rule:

https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-create-rule-schedule.html