Search code examples
pythontags

How could go through two tags for processing ec2 instances


Dear friends and gurus here:

I am working on a python script to power off/on instances based on two tag values. I have two tags assigned to each ec2 instances. One is "schedule_name" tag which defines what schedule it should be powered off/on, the other is "skip_shutdown" tag which should remove that instance from shutdown schedule and reset its value to "no". (this works as a temporary switch for un-Normal reason not powering it off)

I got trapped here by how to use stacked "tag['key']

here is my code

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

Solution

  • In for-loop you should only get values and assing to variables.

    And after for-loop you should use both variables to on/off

    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)