Lambda, AWS and Python Automation Management Operations - Auto Boot and Shut-down

Posted by BinaryDragon on Sat, 05 Oct 2019 10:58:44 +0200

The last beans have been configured to add boto3 and pyboto3 to PyCharm, so you can write scripts directly in your own PyCharm.

Here's an example of traversing all region s to find EC2, turning it off if the state is turned on, or vice versa, turning it on if the state is turned off.

import boto3

def lambda_handler(event, context):

    # Get list of regions
    ec2_client = boto3.client('ec2')
    regions = [region['RegionName']
               for region in ec2_client.describe_regions()['Regions']]

    # Iterate over each region
    for region in regions:
        ec2 = boto3.resource('ec2', region_name=region)

        print("Region:", region)

        # Get only running instances
        instances = ec2.instances.filter(
            Filters=[{'Name': 'instance-state-name',
                      'Values': ['running']}])

        #Stop the instances
        for instance in instances:
            instance.stop()
            print('Stopped instance: ', instance.id)

        # instances = ec2.instances.filter(
        #     Filters=[{'Name': 'instance-state-name',
        #               'Values': ['stopped']}])
        #
        # for instance in instances:
        #     instance.start()
        #     print('Start instance: ', instance.id)

if __name__ == '__main__':
    lambda_handler(0,0)

It's a job to execute it.

C:\Users\yuan\PycharmProjects\aws\venv\Scripts\python.exe C:/Users/yuan/PycharmProjects/aws/StopInstance.py
Region: eu-north-1
Region: ap-south-1
Region: eu-west-3
Region: eu-west-2
Region: eu-west-1
Region: ap-northeast-2
Region: ap-northeast-1
Region: sa-east-1
Region: ca-central-1
Region: ap-southeast-1
Region: ap-southeast-2
Stopped instance:  i-0bb70cc9666ce2af3
Region: eu-central-1
Region: us-east-1
Stopped instance:  i-00e9dc7c254dbe497
Region: us-east-2
Region: us-west-1
Region: us-west-2

Then we create a new function in Lambada of aws, where I have customized a role to ensure that it has the power to turn on and off ec2.

The authority of IAM is as follows:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeInstances",
        "ec2:DescribeRegions",
        "ec2:StartInstances",
        "ec2:StopInstances"
      ],
      "Resource": "*"
    }
  ]
}

Copy function

Next, add a new rule to cloudwatch

Create a wizard, select schedule here, and use cron's expression here. Note that it's GMT time, so you need to switch between yourself and local time.

After writing, he will have a friendly prompt interface.

Complete creation

Returning to Lambda's interface, you can see that his trigger has one more CloudWatch Events

After waiting for execution, you can view the log

You can also confirm that the EC2 service is shut down.

Topics: AWS Pycharm Python Lambda