简体   繁体   English

如何跨所有 AWS 区域调用 Lambda 函数?

[英]How do I invoke Lambda function across all AWS regions?

I have the below lambda function which stops all the Ec-2 instances with the AutoOff_uat tag.我有以下 lambda 函数,它使用 AutoOff_uat 标记停止所有 Ec-2 实例。 If I want to run this lambda across two regions us-east-1 and us-east-2.如果我想在两个区域 us-east-1 和 us-east-2 上运行这个 lambda。 what modifications do i need to make我需要做哪些修改

import boto3
import logging

#setup simple logging for INFO
logger = logging.getLogger()
logger.setLevel(logging.INFO)

#define the connection
ec2 = boto3.resource('ec2')



def lambda_handler(event, context):
# Use the filter() method of the instances collection to retrieve
# all running EC2 instances.
filters = [{
        'Name': 'tag:AutoOff_uat',
        'Values': ['True']
    },
    {
        'Name': 'instance-state-name', 
        'Values': ['running']
    }
]

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

#locate all running instances
RunningInstances = [instance.id for instance in instances]

#print the instances for logging purposes
#print RunningInstances 

#make sure there are actually instances to shut down. 
if len(RunningInstances) > 0:
    #perform the shutdown
    shuttingDown = ec2.instances.filter(InstanceIds=RunningInstances).stop()
    print shuttingDown
else:
    print "Nothing to see here"

You can pass the region to the resource when you create it可以在创建时将区域传递给资源

ec2 = boto3.resource('ec2', region_name='us-east-2')

I would recommend wrapping all of your code in a function which takes the region as an argument and then iterate over a list of regions you want to operate on.我建议将所有代码包装在一个函数中,该函数将区域作为参数,然后遍历要操作的区域列表。

import boto3
import logging

#setup simple logging for INFO
logger = logging.getLogger()
logger.setLevel(logging.INFO)


def shutdown_instances(region):
    #define the connection
    ec2 = boto3.resource('ec2', region=region)

    # Use the filter() method of the instances collection to retrieve
    # all running EC2 instances.
    filters = [{
            'Name': 'tag:AutoOff_uat',
            'Values': ['True']
        },
        {
            'Name': 'instance-state-name', 
            'Values': ['running']
        }
    ]

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

    #locate all running instances
    RunningInstances = [instance.id for instance in instances]

    #print the instances for logging purposes
    #print RunningInstances 

    #make sure there are actually instances to shut down. 


def lambda_handler(event, context):
    for region in ['us-east-1', 'us-east-2']:
        shutdown_instances(region)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM