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

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

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

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

functions:
  hello:
    handler: hello.handler
    environment:
      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