python - 获取AWS EC2特定标签/值组合+实例ID

标签 python python-3.x aws-lambda boto3

我是 Python 和编程新手。我需要使用 Python 3.7 创建一个 Lambda 函数,该函数将查找特定的标签/值组合并返回标签值和实例 id 。我可以用我当前的代码来获得两者,但我很难弄清楚如何将它们结合起来。 boto3.resource 为我提供标签值,boto3.client 为我提供实例 ID。

我有 EC2 实例(1000 个),我们需要监控标签“expenddate”的标签值,并将该值 (mm/dd/yy) 与当前日期 (mm/dd/yy) 进行比较,并在“expenddate”时发出警报expenddate' 值小于当前日期。


    import boto3
    import collections
    import datetime
    import time
    import sys

    from datetime import date as dt

    def lambda_handler(event, context):
        today = datetime.date.today()
        mdy = today_string = today.strftime('%m/%d/%y')
        ec2 = boto3.resource('ec2')
        for instance in ec2.instances.all():
            if instance.tags is None:
                continue
            for tag in instance.tags:
                if tag['Key'] == 'expenddate':
                    if (tag['Value']) <= mdy:
                        print ("Tag has expired!!!!!!!!!!!")
                    else:
                        print ("goodby")
        client = boto3.client('ec2')
        resp = client.describe_instances(Filters=[{
            'Name': 'tag:expenddate',
            'Values': ['*']
        }])

        for reservation in resp['Reservations']:
            for instance in reservation['Instances']:
                print("InstanceId is {} ".format(instance['InstanceId']))

我希望最终得到一个组合的实例 ID 和标签值或两个稍后可以组合的变量。

最佳答案

改变

print ("Tag has expired!!!!!!!!!!!")

# initialise array 
expiredInstances=[]
.
.
.
.
.
print ("%s has expired" % instance.id)
expiredInstances.append({'instanceId':instance.id,'tag-value':tag['Value']})

这将为您提供带有标签值的 instanceId 数组

关于python - 获取AWS EC2特定标签/值组合+实例ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55751818/

相关文章:

python - 如何在 Tensorflow 2 中获取 Conv2D 内核值

python - 值错误 : Received a null pointer

python - Asyncpg 池随机停止响应

python - 如何使用递归计算嵌套列表的最大长度?

Node.js:从 s3 下载文件并将其解压缩为字符串

javascript - 在 AWS lambda 函数中从 s3 分块读取 csv 文件

python - 对在 django 中将 CSV 文件制作成 ZIP 文件感到困惑

android - Android 上的 Kivy : Keep Kivy clock running even when app is minimized

amazon-web-services - 为什么 Dynamodb.put 在 Lambda 函数中不起作用?返回空值。如何调试?

python - CreateView 创建两个模型对象