0

I hope I don't offend anyone with this code but I'm really new to Python. So I have an empty dictionary that have these blank key list that's suppose to go through the for loop and then populate the values, after it's done iterating it should return a full dictionary, but instead it's all blank. At first I thought it was an issue with the dic not keeping their items and that's why I concatenated the lists, bu the output is still the same, the output is:

{'missingtagkeys': [], 'missingtagvalues': [], 'incorrecttagvalues': [], 'unknowntagvalues': [], 'correcttags': []}

Any help on this would be much appreciated, I've been stuck on this a while...thank you!

import boto3   
import collections     
import datetime       
import sys
import json 
import logging
from botocore.exceptions import ClientError

sns = boto3.client('sns', 'us-east-1')
ec = boto3.client('ec2', 'us-east-1')     
ec2 = boto3.resource('ec2', 'us-east-1')     
sns_client = boto3.client('sns')

def lambda_handler(event, context):           
    # instance_ids = []
    reservations = ec.describe_instances().get('Reservations', [])
    
    return_value = {} #creates empty dictionary#
    return_value['missingtagkeys'] = [] #within return values dictionary, create a missing tag key list#
    return_value['missingtagvalues'] = [] #within return values dictionary, creates a missing tag values key list#
    # return_value['incorrecttagkeys'] = [] #within return values dictionary, create a incorrect tag key list#   
    return_value['incorrecttagvalues'] = [] #within return values dictionary, create a incorrect tag value list#
    return_value['unknowntagvalues'] = [] #within return values dictionary, create a unknown tag value list#
    return_value['correcttags'] = [] #within return values dictionary, create a unknown tag value list#
        
    TopicArn = 'arn:aws:sns'
    Subject = 'Incorrect Tags Dectected'
    Message = str(return_value)
          
    buildertag = [{
        "Key": "builder",
        "Value": "unknown"
    }]
    
    for reservation in reservations:
        for instance in reservation['Instances']:
            tags = {}
            for tag in instance['Tags']:
                tags[tag['Key']] = tag['Value']
            
            # Checks if builder tag exist and adds if it doesn't #
            if not 'builder' in tags:
                missingtag = (instance['InstanceId'] + " does not have builder tag. Adding 'builder' tag with value of 'unknown'.")
                print(instance['InstanceId'] + " does not have builder tag. Adding 'builder' tag with value of 'unknown'.")
                ec.create_tags(Resources=[instance["InstanceId"]], Tags=buildertag)
                return_value['missingtagkeys'] = return_value['missingtagkeys'] + [return_value['missingtagkeys'].append(missingtag)]

            # Checks for null tag value and print output #                                        
            elif tags['builder'] in ['']:
                print(instance['InstanceId'] + " has no value for builder tag.") 
                missingtag = (instance['InstanceId'] + " has no value for builder tag.") 
                ec.create_tags(Resources=[instance["InstanceId"]], Tags=buildertag)
                return_value['missingtagvalues'] = return_value['missingtagvalues'] + [return_value['missingtagvalues'].append(missingtag)]

            # # Checks for unknown tag value and print output #                                         
            elif tags['builder'] in ['unknown']:
                print(instance['InstanceId'] + " has an unknown builder tag value.")
                missingtag = (instance['InstanceId'] + " has an unknown builder tag value.") 
                return_value['unknowntagvalues']  = return_value['unknowntagvalues'] + [return_value['unknowntagvalues'].append(missingtag)]   

            # Checks for builder tags equal to approved values and print output #                                        
            elif tags['builder'] in ['a', 'b', 'c', 'd', 'e']:
                print(instance['InstanceId'] + " has an unknown builder tag value.")
                missingtag = (instance['InstanceId'] + " has an approved builder tags.") 
                return_value['correcttags'] = return_value['correcttags'] + [return_value['correcttags'].append(missingtag)]   
                
            # Checks for builder tags equal to unapproved values and print output #                                        
            elif tags['builder'] not in ['a', 'b', 'c', 'e', 'f']:
                print(instance['InstanceId'] + " has a incorrect builder tag value.")
                missingtag = (instance['InstanceId'] + " has a incorrect builder tag value.") 
                return_value['incorrecttagvalues'] = return_value['incorrecttagvalues'] + [return_value['incorrecttagvalues'].append(missingtag)]
    
    sns_client.publish(
    TopicArn=TopicArn,
    Subject=Subject,
    Message=Message
    )   

                
skyfire123
  • 31
  • 6
  • `append()` modifies the list in place, it doesn't return the modified list. – Barmar Jun 10 '22 at 01:50
  • `return_value['missingtagvalues'] = return_value['missingtagvalues'] + [return_value['missingtagvalues'].append(missingtag)]` could (should?) just be `return_value['missingtagvalues'].append(missingtag)` – Nick Jun 10 '22 at 01:53
  • Also check out [defaultdict](https://docs.python.org/3/library/collections.html#collections.defaultdict), it will make setting up `return_values` much easier – Nick Jun 10 '22 at 01:54
  • Finally you don't seem to be returning any value from your function. Not sure if that is intentional or not? – Nick Jun 10 '22 at 01:54
  • I tried using return_value['missingtagvalues'].append(missingtag) and the came back with no results, so I tried this route, same output. I have this going to a sns topic which appears to work if since the there is output, albeit blank. I did return a response previously but it broke the loop and only reported the first thing it came across, I'm thinking I don't they that setup correct either. I will check out the stuff you referenced. Thank you for the response. – skyfire123 Jun 10 '22 at 02:38
  • **Please** read [mre]. – Karl Knechtel Sep 14 '22 at 15:45
  • Thanks for the read, I will consider definitely keep it in mind for the future. – skyfire123 Sep 16 '22 at 04:04

0 Answers0