Jack
Jack

Reputation: 11

Need to write to a file in AWS Lambda AND access it in the next execution

So, the function I have written involves saving a string to a text file at the end of each execution, and then calling that string in the next. It works fine locally, but not on Lambda. From what I can find, it looks like Lambda only supports writing to files in a /tmp folder, but it would only last for one execution, which doesn't work for me. How do I go about this?

Here is the relevant code, it's part of a tweepy bot.

def reply():
    with open('lastid.txt', 'r+') as mf:
        last = mf.readline()
        response = client.get_users_mentions(user_id, since_id=last)
        for tweet in response.data:
            text = tweet.text
            id = tweet.id
            if any(x in text.lower() for x in strings):
                client.create_tweet(in_reply_to_tweet_id=id, text=greet)
            else:
                client.create_tweet(in_reply_to_tweet_id=id, text=reply)
            mf.write(str(tweet.id))

Thank you very much for any help! Maybe the answer is obvious but honestly my brain is a little fried at the moment.

Upvotes: 0

Views: 2573

Answers (2)

Mark B
Mark B

Reputation: 200476

Files written to /tmp aren't necessarily removed between executions. They can be retained across multiple Lambda executions if container reuse happens.

However, there is no guarantee that this will happen. And if you want to retain the file across new Lambda function version deployments then it isn't possible at all using /tmp.

Your options are:

Given your use case I would suggest the EFS solution.

Upvotes: 0

Vasu Kandimalla
Vasu Kandimalla

Reputation: 100

You can write to an s3 file and use it in the next execution. Before that, you need to give access to your lambda function to access the s3 location.

Upvotes: 1

Related Questions