Can we set the environment variable of AWS python lambda on invocation

Viewed 1963

I have a python AWS lambda that hits a REST endpoint, if the service/endpoint is down or unreachable I want to send a notification to a teams/slack channel.

I don't want to keep sending this notification for every message while the service is down. I would like to send one message the first time it is down and then send another when it is back up.

I was thinking of having an environment variable SERVICE_UP = true. If we get an error saying service is down we notify the channel and set SERVICE_UP = false, when it changes again we send a notification saying service back up and set SERVICE_UP = true.

Pseudo code for what I am trying to achieve or else open to other suggestions, not sure i DynamoDB table might be overkill for what i am trying to achieve?

if (SERVICE_UP == true):
   if (failed_call):
     send_notification()
     SERVICE_UP = false;

if (SERVICE_UP == false):
   if (successful_call):
     send_notification()
     SERVICE_UP = true;
2 Answers

Sadly you can't set the environment variables during invocation, as they are part of lambda's configuration. Thus you can use update-function-configuration API call to set their values in unpublished function only. If the function is published (i.e. it has a version) then the environment variables are immutable.

As a workaround you can store variable SERVICE_UP externally, e.g. in AWS Systems Manager Parameter Store to persist its value between invocations.

The other workaround, if your function is unpublished, would be to use AWS SDK in the function to call update-function-configuration so that the function updates its own environment variables.

For short term storage of the SERVICE_UP value, you could use AWS Lambda execution context which persists between function executions for some time. But its not permanent.

Related