AWS Lambda 停止 EC2,但排除两个实例



我们正在寻找 AWS Lambda 脚本来停止特定区域中的所有 EC2 实例 期望两个实例

首先,您需要为要停止的实例添加标签,例如 AutoStop 标签,并为它们分配值 True,然后运行以下代码:

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',
'Values': ['True']
},
{
'Name': 'instance-state-name', 
'Values': ['running']
},
{
'Name': 'region', 
'Values': ['us-east-1'] #replace it with your region
}
]
#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"

最新更新