上一篇豆子已經(jīng)配置在PyCharm里面添加了boto3和pyboto3,因此寫(xiě)腳本的時(shí)候可以直接在自己的PyCharm里面編寫(xiě)。

下面是一個(gè)例子遍歷所有的region查找EC2,如果狀態(tài)是開(kāi)機(jī),那就關(guān)掉;或者倒過(guò)來(lái)也可以寫(xiě)成 如果是關(guān)機(jī)狀態(tài),就開(kāi)機(jī)。

            
              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)
            
          

執(zhí)行一下是工作的

            
              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
            
          

然后我們?cè)赼ws的Lambda里創(chuàng)建一個(gè)新的函數(shù), 這里我已經(jīng)自定義了一個(gè)role了,確保這個(gè)role可以對(duì)ec2有開(kāi)機(jī)和關(guān)機(jī)的權(quán)限

Lambda,AWS和Python的自動(dòng)化管理操作 - 自動(dòng)開(kāi)機(jī)和關(guān)機(jī)_第1張圖片

IAM的權(quán)限如下所示:

            
              {
  "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的自動(dòng)化管理操作 - 自動(dòng)開(kāi)機(jī)和關(guān)機(jī)_第2張圖片

拷貝函數(shù)上來(lái)

Lambda,AWS和Python的自動(dòng)化管理操作 - 自動(dòng)開(kāi)機(jī)和關(guān)機(jī)_第3張圖片

接下來(lái) 在cloudwatch里面添加一個(gè)新的rule

Lambda,AWS和Python的自動(dòng)化管理操作 - 自動(dòng)開(kāi)機(jī)和關(guān)機(jī)_第4張圖片

創(chuàng)建向?qū)?,這里選擇schedule,這里使用 cron的表達(dá)式,注意他是GMT的時(shí)間,因此需要自己和本地時(shí)間轉(zhuǎn)換一下

Lambda,AWS和Python的自動(dòng)化管理操作 - 自動(dòng)開(kāi)機(jī)和關(guān)機(jī)_第5張圖片

寫(xiě)好之后他會(huì)有個(gè)友好的提示界面

Lambda,AWS和Python的自動(dòng)化管理操作 - 自動(dòng)開(kāi)機(jī)和關(guān)機(jī)_第6張圖片

完成創(chuàng)建

Lambda,AWS和Python的自動(dòng)化管理操作 - 自動(dòng)開(kāi)機(jī)和關(guān)機(jī)_第7張圖片

回到Lambda的界面, 可以看見(jiàn)他的觸發(fā)器多了一個(gè)CloudWatch Events

Lambda,AWS和Python的自動(dòng)化管理操作 - 自動(dòng)開(kāi)機(jī)和關(guān)機(jī)_第8張圖片

等待執(zhí)行之后,可以查看日志

Lambda,AWS和Python的自動(dòng)化管理操作 - 自動(dòng)開(kāi)機(jī)和關(guān)機(jī)_第9張圖片

也可以確認(rèn)EC2 服務(wù) 的確關(guān)機(jī)了

Lambda,AWS和Python的自動(dòng)化管理操作 - 自動(dòng)開(kāi)機(jī)和關(guān)機(jī)_第10張圖片