This rule raises an issue when AWS Lambda handlers write to the /tmp directory without properly cleaning up temporary files before function completion.
AWS Lambda provides a temporary file system at /tmp for each execution environment. However, the contents of /tmp can persist across multiple invocations of the same Lambda function instance during "warm starts." When temporary files are not cleaned up, they remain available to subsequent invocations of the same function instance.
This can lead to serious security and reliability issues: sensitive data from one invocation might leak to unrelated subsequent invocations, disk space can be exhausted causing function failures, and stale data from previous runs can cause unexpected behavior and hard-to-debug issues.
Always clean up temporary files before your Lambda function completes. It is possible to use the tempfile module to create temporary
files that will be automatically deleted.
Otherwise, use a try…finally block to ensure cleanup happens even if errors occur during processing.
def lambda_handler(event, context):
file_path = '/tmp/temp_data.txt' # Noncompliant
with open(file_path, 'w') as f:
f.write("Something")
import tempfile
def lambda_handler(event, context):
with tempfile.NamedTemporaryFile() as f: # Compliant
f.write("Something")