Lambda,AWS和Python的自動化管理操作 - 自動開機和關機

上一篇豆子已經配置在PyCharm裏面添加了boto3和pyboto3,因此寫腳本的時候可以直接在自己的PyCharm裏面編寫。

下面是一個例子遍歷所有的region查找EC2,如果狀態是開機,那就關掉;或者倒過來也可以寫成 如果是關機狀態,就開機。

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)

執行一下是工作的

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

然後我們在aws的Lambda裏創建一個新的函數, 這裏我已經自定義了一個role了,確保這個role可以對ec2有開機和關機的權限

Lambda,AWS和Python的自動化管理操作 - 自動開機和關機

IAM的權限如下所示:

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

Lambda,AWS和Python的自動化管理操作 - 自動開機和關機

拷貝函數上來

Lambda,AWS和Python的自動化管理操作 - 自動開機和關機

接下來 在cloudwatch裏面添加一個新的rule

Lambda,AWS和Python的自動化管理操作 - 自動開機和關機

創建嚮導,這裏選擇schedule,這裏使用 cron的表達式,注意他是GMT的時間,因此需要自己和本地時間轉換一下

Lambda,AWS和Python的自動化管理操作 - 自動開機和關機

寫好之後他會有個友好的提示界面

Lambda,AWS和Python的自動化管理操作 - 自動開機和關機

完成創建

Lambda,AWS和Python的自動化管理操作 - 自動開機和關機

回到Lambda的界面, 可以看見他的觸發器多了一個CloudWatch Events

Lambda,AWS和Python的自動化管理操作 - 自動開機和關機

等待執行之後,可以查看日誌

Lambda,AWS和Python的自動化管理操作 - 自動開機和關機

也可以確認EC2 服務 的確關機了

Lambda,AWS和Python的自動化管理操作 - 自動開機和關機

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章