Is there a way to insert a timestamp into a Lambda environment variable?

I’m deploying Lambda with sls deploy.

I want to put the deployment time in the Lambda environment variable.
We want to use it in various places to clear the various caches.

Is there a way?!


Of course. In the Serverless Docs see: Reference Variables in Javascript Files

Just add a script such as: gettime.js

module.exports = () => new Date().toISOString()

Reference that in the custom section of your serverless.yml, then reference that as an environment var under your function definition. Or if you want it available to all your functions, define it under provider. Here’s a simple working serverless.yml

service: simple

  deploy-time: ${file(./gettime.js)}

  name: aws
  runtime: nodejs12.x
  stage: ${opt:stage, 'dev'}
  region: ${opt:region, 'us-west-2'}

    handler: hello.handler
      DEPLOY_TIME: ${self:custom.deploy-time}

Then you can access that envVar in your lambda function(hello.js) like so:

const AWS = require('aws-sdk');

exports.handler = async event => {
  const currentTime = new Date().toISOString()
  const deployTime = process.env.DEPLOY_TIME
  return { deployTime, currentTime }
1 Like

Resolved. Thank you.