How can I access option value passed by serverless cli in serverless.ts?

While I using serverless framework using serverless.ts for setting, I got a question.

I can pass the value on serverless cli like this

serverless offline --stage prod

In serverless.yml, we can access this value by ${self:provider.stage} But I cannot access it on serverless.ts. Of course, I know it can replaced to constant variable and don't pass the value on cli. But I worder that I can never access passed value on serverless.ts. Is there any way???


Solution 1:

TL;DR: my workaround was to use the function exported in serverless/lib/utils/resolveCliInput.

I'm not sure if I understood you correctly, but if your question is how to access the values passed to serverless CLI from within serverless.(ts|js) then I have a workaround.

I had this problem and I couldn't find any solution for it after googling for some time, so I started to dig in the serverless source code. I've noticed this file serverless/lib/utils/resolveCliInput that exports a single function that resolves input arguments.

To be honest, I don't know whether we can rely on this function in future versions of the framework (I've tested with version 2.8.0), but here is a working code example:

import resolveCliInput from 'serverless/lib/utils/resolveCliInput';
const { commands, options } = resolveCliInput(process.argv.slice(2));
const stage = options.s ?? options.stage ?? 'dev';

Of course we can use some library for parsing process.argv such as commander or even parse the args in our code.