首页 > 解决方案 > 如何通过两个标签来处理 ec2 实例

问题描述

亲爱的朋友和大师在这里:

我正在编写一个 python 脚本来根据两个标签值关闭/打开实例。我为每个 ec2 实例分配了两个标签。一个是“schedule_name”标签,它定义了它应该关闭/打开的计划,另一个是“skip_shutdown”标签,它应该从关闭计划中删除该实例并将其值重置为“no”。(这作为非正常原因的临时开关不关闭它)

我被如何使用堆叠的“标签['key']困在这里

这是我的代码

for instance in instances:

        for tag in instance.tags:

            if tag['Key'] == 'Schedule_Name':
                
                    if tag['Value'] == 'App' and current_time == app_off.get(current_dayoftheweek):

                        if tag['Key'] == 'skip_shutdown':
                            if tag['Value'] == 'yes':
                                # reset the tag value to "no" for this tag
                            
                            if tag['Value'] == 'no':
                                # add this instance to stopInstances variable to stop it.
                                    stopInstances.append(instance.id)

                        pass
                    pass

标签: pythontags

解决方案


for-loop 中,您应该只获取值并分配给变量。

for-loop 之后,您应该使用这两个变量来打开/关闭

for instance in instances:

    # - before loop `for tag`-       

    Schedule_Name = None
    skip_shutdown = None

    # - loop `for tag`-       
    
    for tag in instance.tags:
        if tag['Key'] == 'Schedule_Name':
            Schedule_Name = tag['Value']
        elif tag['Key'] == 'skip_shutdown':
            skip_shutdown = tag['Value']
            
    # - after loop `for tag`-       
    
    if Schedule_Name == 'App' and current_time == app_off.get(current_dayoftheweek):
        if skip_shutdown == 'yes':
            # reset the tag value to "no" for this tag
        elif tag['Value'] == 'no':
            # add this instance to stopInstances variable to stop it.
            stopInstances.append(instance.id)

推荐阅读