【问题标题】:How could go through two tags for processing ec2 instances如何通过两个标签来处理 ec2 实例
【发布时间】:2021-05-14 23:48:10
【问题描述】:

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

我正在编写一个 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

【问题讨论】:

  • 您应该使用if ... elif ... 而不是嵌套的if ... if.. 并且您应该为外部变量赋值 - 在for-loop 之后检查两个值是否正确。

标签: python tags


【解决方案1】:

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)

【讨论】:

  • 非常感谢您的帮助。对此,我真的非常感激。我现在就实现你的方法。
  • 在 lambda 函数中运行它时出现此错误:“esponse { "errorMessage": "模块 'lambda_function' 中的语法错误:需要缩进块 (lambda_function.py,第 153 行)", " errorType": "Runtime.UserCodeSyntaxError", "stackTrace": [" File \"/var/task/lambda_function.py\" Line 153\n elif tag['Value'] == 'no':\n" ] }
  • ` # - 在循环后for tag- 检查哪个实例需要关闭 if Schedule_Name == 'App' and current_time == app_off.get(current_dayoftheweek): if skip_shutdown == 'yes': # 将此标签的标签值重置为“no” elif tag['Value'] == 'no': # 将此实例添加到 stopInstances 变量以停止它。 stopInstances.append(instance.id) pass`
  • 我不知道如何在 cmets 中格式化我的代码。如何格式化我的代码?
  • ` # - 在循环后for tag- 检查哪个实例需要关闭 if Schedule_Name == 'App' and current_time == app_off.get(current_dayoftheweek): if skip_shutdown == 'yes': # 将此标签的标签值重置为“no” elif tag['Value'] == 'no': # 将此实例添加到 stopInstances 变量以停止它。 stopInstances.append(instance.id) pass `
猜你喜欢
  • 2018-05-10
  • 1970-01-01
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
相关资源
最近更新 更多