Lambda函数根据标记过滤AWS EC2实例?

时间:2017-06-22 17:35:32

标签: python amazon-web-services amazon-ec2 aws-lambda

我正在尝试创建一个Lambda函数,该函数将过滤所有正在运行的实例,查找具有特定标记的实例,然后关闭这些实例。我对使用AWS Lambda相对较新,因此非常感谢任何帮助。这是我到目前为止,我目前只是试图让过滤器工作,因为我已经知道如何关闭Lambda中的实例。我收到的错误是“模块初始化错误”。有什么建议吗?

import boto3
ec2 = boto3.resource('ec2')

def lambda_handler(event, context):
    filters = [{
         'Name': 'tag:Application',
         'Values': ['exampleName']
       },
       {
        'Name': 'tag:Vertical',
        'Values': ['exampleVertical']
     }]

    instances = ec2.instances.filter(Filters=filters)

    RunningInstances = [instance.id for instance in instances]

    if len(RunningInstances) > 0:
       print("found instances with tag")
    else:
        print("none found")

更新:此代码有效并且可以找到实例,问题是由于最初未将适当的角色分配给该函数而引起的。

1 个答案:

答案 0 :(得分:1)

以下是给定代码的stoppingrunning个实例的基本工作代码段 -

from boto3.session import Session
from botocore.exceptions import ClientError

aws_access_key = ''
aws_secret_key = ''
region = ''

def lambda_handler(event, context):
   try:
       sess = Session(aws_access_key_id=aws_access_key,
                   aws_secret_access_key=aws_secret_key)
       ec2_conn = sess.client(service_name='ec2', region_name=region)

       instance_ids = []
       reservations = ec2_conn.describe_instances(
                                Filters=[
                                    {
                                        'Name': 'tag:Application',
                                        'Values': [
                                            'exampleName',
                                        ]
                                    },
                                    {
                                        'Name': 'tag:Vertical',
                                        'Values': [
                                            'exampleVertical',
                                        ]
                                    },
                                    {
                                        'Name': 'instance-state-name',
                                        'Values': [
                                            'running',
                                        ]
                                    },
                                ])['Reservations']

      for reservation in reservations:
          instances = reservation['Instances']
          for instance in instances:
              instance_ids.append(instance['InstanceId'])

      print("Stopping instances: {}".format(','.join(instance_ids)))

      stopped_instances_response = ec2_conn.stop_instances(
                             InstanceIds=instance_ids)

      print(stopped_instances_response)
  except ClientError as e:
     print(e)

P.S:您也可以从环境变量中添加凭据。