【问题标题】:Why does my AWS Lambda script return 'Instances' instead of the instance ID?为什么我的 AWS Lambda 脚本返回“实例”而不是实例 ID?
【发布时间】: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


【解决方案1】:

看起来您的 for 循环部分没有通过 Json Key 值。

使用以下代码使用 Boto3 检索 Instance-Ids

import boto3

ec2 = boto3.client('ec2')

schedulers = ec2.describe_instances(InstanceIds=['i-xxxxxxxx'])

for i in schedulers['Reservations']:
   print i['Instances'][0]['InstanceId']

您可以在代码中实现相同的 for 循环(如果需要多个实例,请使用循环)

希望这会有所帮助。

【讨论】:

  • 啊,这让我朝着正确的方向前进。必须先解析 Reservation 字典,然后再解析结果的保留列表。感谢您的帮助!
猜你喜欢
  • 2019-05-31
  • 2017-04-26
  • 1970-01-01
  • 2023-03-07
  • 2021-05-25
  • 2021-05-11
  • 2016-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多