Search code examples
pythonamazon-web-servicesaws-lambdaboto3

Using boto3 to update multiple resources with different values in single lambda script


I want to iterate over all the resources in my account and update them based on an excel file which has some values that need to be updated. The problem I'm running into with my current code is it will only update the final value that is returned and not the others. How do i get it to update all resources?

import boto3

s3_client = boto3.client('s3')
client = boto3.client('resourcegroupstaggingapi')

def get_resource_tag(resource_name):
#this is an example, will have unique values returned from here. 
     return ['uniqueexample','value']

def update_resources_dict(resource):
    resource_name = resource["ResourceARN"]
    tag_to_update = get_resource_tag(resource_name)
    resource_list = [resource_name]
    return client.tag_resources(ResourceARNList =resource_list , Tags = {tag_to_update[0]:tag_to_update[1] })

def lambda_handler(event, context):
    all_resources=client.get_resources(ResourcesPerPage = 100)
    for resource in all_resources["ResourceTagMappingList"]:
        update_resources_dict(resource)

This function does not update each of the reosurces I use client.tag_resources on. How would i fix that?


Solution

  • Needed to append it to a something and return that. The following code solved it:

    import boto3
    
    s3_client = boto3.client('s3')
    client = boto3.client('resourcegroupstaggingapi')
    
    def get_resource_tag(resource_name):
         return ['uniqueexample','value']
    
    def update_resources_dict(resource):
        resource_name = resource["ResourceARN"]
        tag_to_update = get_resource_tag(resource_name)
        resource_list = [resource_name]
        return client.tag_resources(ResourceARNList =resource_list , Tags = {tag_to_update[0]:tag_to_update[1] })
    
    def lambda_handler(event, context):
        all_resources=client.get_resources(ResourcesPerPage = 100)
        rd = {}
        for resource in all_resources["ResourceTagMappingList"]:
            print(resource)
            rd[resource['ResourceARN']] = update_resources_dict(resource)
        return rd
        
           ```