Skip to content

Support Promises in variables referencing javascript ( ${file(file.js):value} ) #3073

Closed

Description

@tgjorgoski

This is a Feature Proposal

Description

Serverless has very nice variables support. Among other things it allows for variable values to be generated dynamically by specifying functions to call. E.g. from the documentation:

${file(../myCustomFile.js):hello}

Here the hello method from myCustomFile.js can return e.g. some string, and the variable would be replaced with that string.

However, in some cases figuring out the value might require async. calls. It would be nice if serverless would accept Promises as return values instead of just values.

The exact use case I was trying to do is retrieving some secret ID from an s3 bucket, and putting it in the lambda environment variables.
As far as I can see, there is no other way to use the result of this snippet within the sls (except writing a plugin, I guess).

    bucket.getObject(
        {
            Bucket: "secret-data-bucket",
            Key: "secret-data.json"
        }
    ).promise()
    .then(data => {
        let object = JSON.parse(data.Body.toString());
        resolve(object.secretID);
    })

Activity

  1. hauboldj commented on Feb 7, 2017

    @hauboldj

    @tgjorgoski
    As a kinda hacky work around you can do this.
    In myCustomFile.js

    'use strict'
    
    const childProcess = require('child_process')
    module.exports.get = () => {
      let command = `node -e "(new(require('aws-sdk').S3)()).getObject({Bucket:'secret-data-bucket',Key:'secret-data.json'}).promise().then(r=>console.log(r.Body.toString()))"`
      return JSON.parse(childProcess.execSync(command))
    }
    

    And in the serverless.yml

    MY_SECRET_VALUE: ${file(./myCustomFile.js):get.secretValue}
    
  2. shortjared commented on Feb 17, 2017

    @shortjared
    Contributor

    Quick update to this... @hauboldj thought the above turned out to be a bit hacky... new and improved version...

    'use strict'
    
    const childProcess = require('child_process')
    module.exports.get = () => {
      let command = 'node secrets.js'
      return JSON.parse(childProcess.execSync(command))
    }
    
    if (require.main === module) {
      let aws = require('aws-sdk')
      let s3 = new aws.S3()
      s3.getObject({
        Bucket: 'your-bucket',
        Key:'secrets.json'
      }).promise()
      .then(r => console.log(r.Body.toString()))
      .catch(console.log)
    }
  3. hauboldj commented on Feb 17, 2017

    @hauboldj

    The above file is secrets.js if that wasn't obvious.

  4. jthomerson commented on Apr 16, 2017

    @jthomerson
    Contributor

    I was looking to do something very similar, and found your issue before creating one of my own. My goal is to automatically add the current code version - git hash - as a CloudFormation stack tag so that it's easy to keep track of exactly which version of each service is deployed in each region. So, I wanted to use a JS variable file and need it to support asynchronous calls since obtaining the git version would require async work. I'm impressed by the @hauboldj and @shortjared hacks!

    @flomotlik @pmuens or other core guys - I'm willing to contribute work on this - a pull request - if you give an indication that you would accept this feature. Do you have any guidance on how you'd like it done? I just don't want to put a bunch of effort into it and then find out that you don't agree with the feature or have a specific way you want it done. Thanks!

  5. pmuens commented on Apr 17, 2017

    @pmuens
    Contributor

    @jthomerson thanks for picking this up 👍

    Sounds like a good and useful addition. Any PRs / contributions are highly welcomed! Do you have any plans how this would be implemented?

  6. jthomerson commented on Apr 18, 2017

    @jthomerson
    Contributor

    @pmuens looking at this more, it turns out to be a lot more than I had expected. I'd expected that variables resolution was somewhat async-ready. Turns out it's not. Here's some more details.

    At a minimum, the line that invokes the function in the JS file would need to support resolving a promise. Unfortunately, the entire Variables class is written in such a way that everything it does is synchronous, which really makes that a pain. So, a bunch of code in the Variables class would need to be rewritten. Of course, then there are the callers to the methods on the Variables class, which are currently expecting the the population of all variables to be synchronous, would also need to be adjusted to allow for the new async return of the population process. I haven't looked into how hard that would be yet.

    What I think would be a natural and very necessary extension of this work would be to allow you to call a JS file and pass a function arguments to resolve variables. Consider a case where you have a piece of config in a configuration database table (or any other external system), and you want your serverless template to be able to pull a value from the config DB and use it. If you could pass arguments to the JS function, you could make it extensible. For example, the usecase that @tgjorgoski first posted could be more extensible by allowing for this:

    custom:
      someValue: ${file(./variables-helpers.js):getFromS3(secret-data-bucket, secret-data.json)}

    In that case your JS file would be something like:

    module.exports = {
       getFromS3: function(bucketName, key) {
          return somePromiseThatLoadsJSONFrom(bucketName, key);
       }
    };

    Does that make sense?

    I'm not sure now that I'll have time to do all the work entailed in re-writing the Variables class to be async-ready, so I may not be able to make a PR for this any time soon, but wanted to pass along the suggestion on the ability to pass function arguments as I think that makes the JS-based-vars functionality 1,000x more flexible and useful.

  7. pmuens commented on Apr 18, 2017

    @pmuens
    Contributor

    Hey @jthomerson thanks for digging into this and taking the time to write up a proposal for it 👍

    Really appreciate it!

    Your proposal sounds good to me 👍 . Wonder what others think about it.

    🤔 the sync code of the variable system is something I haven't thought about. Not sure if updating the variables system codebase to work async is worth the effort to support async JavaScript functions.

    Just saw the utils repo where the hack to work with async functions is described. Maybe it's a worthwile approach for now and using async functions via the variable system is more like an edge case scenario.

    Any thoughts @eahefnawy

  8. added this to the 1.13 milestone on Apr 25, 2017
  9. eahefnawy commented on May 3, 2017

    @eahefnawy
    Contributor

    Hey all, as requested, we just added support for promises in the variable system in #3554. With this PR, if your JS file is returning a promise, the variable system will successfully resolve it. This is a good step forward new async sources we might want to add in the future as well 😉

    Please try it out and let me know if I missed anything, otherwise this will be merged soon 😊

  10. zoellner commented on Dec 17, 2018

    @zoellner
    Contributor

    It seems that the comment from @jthomerson got lost. Is support for function arguments planned? Should it be tracked in a new Feature Proposal Issue?

  11. dschep commented on Dec 19, 2018

    @dschep
    Contributor

    Is support for function arguments planned?

    not at the moment AFAIK

    Should it be tracked in a new Feature Proposal Issue?

    feel free to open an issue, but I'm not 100% we want to implement that. The variable system is complicated enough as it is 😉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions