https://serverless-stack.com/ logo
#help
Title
# help
g

Geoff Seemueller

05/06/2022, 3:56 PM
I'm trying to set up database migrations with
sst.Script
+ `stack.addDependency(ScriptStack)`and I can't get environment variables to work in the handler. I'm consuming environment variables from a local
.env
and referencing them via
process.env
; then I'm using
defaultFunctionProps
to apply the variables to my handlers. It appears the environment variables are empty at execution. Is there anything special I need to do?
f

Frank

05/06/2022, 4:04 PM
Hey @Geoff Seemueller, that should work, can I see what your
sst.Script
construct looks like?
g

Geoff Seemueller

05/06/2022, 4:08 PM
Copy code
import * as sst from "@serverless-stack/resources";

export default class DatabaseMigrationsStack extends sst.Stack {
    script: sst.Script | undefined;

    constructor(scope: <http://sst.App|sst.App>, id: string, props?: any) {
        super(scope, id, props);
        this.script = new sst.Script(this, "MyDatabaseMigrations", {
            defaultFunctionProps: {
                environment: {
                    X_ACCOUNT: process.env.X_ACCOUNT!,
                    X_USERNAME: process.env.X_USERNAME!,
                    X_PASSWORD: process.env.X_PASSWORD!,
                    X_DATABASE: process.env.X_DATABASE!,
                    X_ROLE: process.env.X_ROLE!,
                    X_SCHEMA: process.env.X_SCHEMA!
                },
            },
            onCreate: "src/x/migrations.apply"
        })
    }
}
f

Frank

05/06/2022, 4:23 PM
can u do
console.log(process.env.X_ACCOUNT)
right after the
super()
line, and then run
sst build
, does it have a value?
g

Geoff Seemueller

05/06/2022, 4:24 PM
undefined
Ok
It's only picking up variables from
.env
but not
.env.*
works with
.env.local
I'm using a custom suffix on the env file
f

Frank

05/06/2022, 4:41 PM
I see. Which suffix did u use? and what stage did u deploy to?
g

Geoff Seemueller

05/06/2022, 5:03 PM
was trying to use
.env.dbvendor
and stage was dev. I switched it over to
.env.local
and it works like a charm
thanks for the help Frank!
Loving the product
f

Frank

05/06/2022, 9:44 PM
Ah the suffix needs to match the stage name. ie.
.<http://env.dev|env.dev>
will work.
Anything u don’t want to commit should go into
.env.local
and
.env.local
should be git ignored.
4 Views