1

I'm a new learner for AWS Lambda.

I'm trying to get data from AWS Cost Explorer and send a slack daily.

The data should be descending order but it's not. Can you please give some tips for my code?

AWS Lambda seems not to allow to use .getValue() for sort function.

def lambda_handler(event, context):
    client = boto3.client('ce')
    
    #get cost for each service daily
    serviceCost = get_daily_serviceCost(client)
        
    (title, detail) = create_message(totalCost, serviceCost)
    
    #transfer message to slack
    post_slack(title, detail)
    


def get_daily_serviceCost(client) -> list:
    
   
    today = datetime.date.today()
    yesterday = datetime.date.today() - datetime.timedelta(days=1)
    
  
    price = client.get_cost_and_usage(
        TimePeriod={
            'Start':datetime.date.strftime(yesterday, '%Y-%m-%d'),
            'End':datetime.date.strftime(today, '%Y-%m-%d')
        },
        Granularity='DAILY',
        Metrics=['BlendedCost'],
        GroupBy=[
            {
                'Type':'DIMENSION',
                'Key':'SERVICE'
            }
        ]
    )
    
    billings = []
    for item in price['ResultsByTime'][0]['Groups']:
        billings.append({
            'service_name':item['Keys'][0],
            'billing':item['Metrics']['BlendedCost']['Amount']
        })
    return billings
    

def create_message(serviceCost:list) -> (str):
    
    
    yesterday = datetime.date.today() - datetime.timedelta(days=1)
   
    details = []         

    for item in serviceCost:
        service_name = item['service_name']
        billing = round(float(item['billing']),2)
        if billing == 0.00:
            continue
        details.append({service_name, billing})
       
    for check in details:
        print(check)
  
    test = []
    for what in serviceCost:
        test.append({service_name, billing})
        # print(what)
    test.sort(key=lambda k: k[1], reverse=True)
John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
  • AWS Lambda is just a virtual computing environment. It does not impact Python code in any way. Therefore, your issue is with correctly using Python on your `test` object, with nothing to do with AWS Lambda. Please edit your question and show us the contents of `test` both before and after calling `test.sort()`. – John Rotenstein Jul 18 '21 at 03:35
  • In the code there is no `getValue`. So its not clear what are you referring to? – Marcin Jul 18 '21 at 07:13
  • So your question is around your last line of code, and you want to do this? https://stackoverflow.com/questions/20944483/python-3-sort-a-dict-by-its-values – Adam Smooch Oct 03 '21 at 13:12

0 Answers0