【发布时间】:2017-01-20 03:46:35
【问题描述】:
下面是我的 Lambda 脚本,它正在备份我的一些 EC2 实例。我在赋值后立即打印出 instanceId 的值,令我惊讶的是,它返回了字符串“Instances”而不是实例 ID。我在这里检查了预期的响应格式:http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_instances,我相信我的通话是正确的。我首先从列表中获取实例项 (schedule_instances = schedulers['Instances']),然后尝试从该新列表中获取实例 ID。它是否正确?我对获取 VolumeId 也有类似的疑问。
from __future__ import print_function
import json
import boto3
import datetime
import time
ec2 = boto3.client('ec2')
def lambda_handler(event, context):
try:
print("Creating snapshots on " + str(datetime.datetime.today()) + ".")
schedulers = ec2.describe_instances(MaxResults=50, Filters=[{'Name':'tag:GL-sub-purpose', 'Values':['Schedule']}])
print("Performing backup on " + str(len(schedulers)) + " schedules.")
successful = []
failed = []
schedule_instances = schedulers['Instances']
for s in schedulers:
try:
instanceId=s['InstanceId']
print (instanceId)
snapshotDescription = instanceId + "-" + str(datetime.date.today().strftime('%Y-%m-%d')) + "-46130e7ac954-automated"
ec2.create_snapshot(
VolumeId=s['VolumeId'],
Description=snapshotDescription
)
successful.append(instanceId)
except Exception as e:
print(e)
failed.append(instanceId + " :\t" + str(e))
print("Performed backup on " + str(len(successful)) + " schedulers. Failed backup on " + str(len(failed)) + " schedulers. ")
sendEmail(successful, failed)
return "Success"
except Exception as e:
print(e)
return "Failed"
【问题讨论】:
-
是否要获取所有匹配过滤器的实例的实例id?有一种更简单的方法可以获取此信息。
-
我的目标是使用我指定的标签遍历列表中的每个实例并为其创建快照。因此,每次循环运行时,我都需要该特定项目的实例 ID。
标签: amazon-web-services aws-lambda boto3