Lambda caching volumes_list causing deletion failure in subsequent runs

I am just rying lambda and got a lambda (python) that deletes available (not in use) ec2 volumes. It’s working fine, but I am using a eventbridge rule to run my lambda every 60 minutes. One thing I am noticing is that somehow it looks like my lambda is caching information. Since it will run the first time, it will find the available volumes and delete them. After 60 minutes, when it runs again, it will find the same volumes as the first time, even thought they’re no longer there… and it will fail to delete because, of course, they’re no longer there. I thought every time my lambda runs, it would run completely clear, Even the list is empty at the beginning of my code as in volumes_list = [] so why on the second run it’s still getting the same list that was found on the first run?

There are two possible things what can cause this:

  1. assuming you are listing available volumes with boto3, it likely returns Deleted ones as well. In such case, when you iterate through your boto3 response with for cycle, check if it’s not Deleted already…
  1. You are not aware of Lambda caching - generally, all code above lambda handler def will be cached between lambda executions. If you move your volumes_list = within lambda handler function, it will be never cached and always initated as empty.

good to know… thank you