簡體   English   中英

如何跨所有 AWS 區域調用 Lambda 函數?

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

我有以下 lambda 函數,它使用 AutoOff_uat 標記停止所有 Ec-2 實例。 如果我想在兩個區域 us-east-1 和 us-east-2 上運行這個 lambda。 我需要做哪些修改

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"

可以在創建時將區域傳遞給資源

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

我建議將所有代碼包裝在一個函數中,該函數將區域作為參數,然后遍歷要操作的區域列表。

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