Code Monkey home page Code Monkey logo

Comments (16)

Enase avatar Enase commented on July 25, 2024 1

Hi @eahefnawy!

I didn't dive deep into your discussion, but I want to share my thoughts about environment in components.

I think there should be a way to pass environment variables from serverless.yml due to the fact that currently everyone must define all the variables manually by copy/paste all the aws components ids/links/etc. I believe it should be a way to set variables with references to other stacks output or other complex logic like this:

component: website
name: XXX
app: XXX

inputs:
  environment:
    AWS_APPSYNC_ENDPOINT: ${cf:${self:provider.stage}-appsync.AppSyncApiUrl}
    VARIABLE_BY_JS: ${file(path/account-id.js):getAccountId}
    OTHER_VARIABLE:
       Fn::ImportValue: sharedValueToImport

I hope you understand the main idea and the reason why it's important.
Thanks in advance.

from website.

eahefnawy avatar eahefnawy commented on July 25, 2024 1

aaah I see. That's what I thought. Ok, we have a solution in place that we will be releasing shortly.

from website.

eahefnawy avatar eahefnawy commented on July 25, 2024

Welcome @gandatandya 🙌

Is this env logic available after the build? The component just takes your dist directory and push it to the cloud. So if it's there it should work fine.

from website.

gandatandya avatar gandatandya commented on July 25, 2024

Thanks for the explanation @eahefnawy.

I was able to configure for multiple environments using the following serverless file structures.
Basically I create an env and yml file for each environment and inside the .env files, I am setting the NODE_ENV variables. And it works!

from website.

eahefnawy avatar eahefnawy commented on July 25, 2024

Thanks @gandatandya that's good to hear 😊

from website.

spencer-wegner avatar spencer-wegner commented on July 25, 2024

Hew @gandatandya and @eahefnawy I'm trying to do the same thing: configure my frontend using this component to point to different api urls based on the NODE_ENV variable. I have different .env files (e.g. .env.stage, .env.prod) for each environment and I am setting the NODE_ENV variable within them. However, none of the environment variables that I put in the .env files including the NODE_ENV variable are available in my application. It looks like the component is setting NODE_ENV=production by default.

Here's one of my .env files for an environment called stage:

# .env.stage
AWS_ACCESS_KEY_ID=XXX
AWS_SECRET_ACCESS_KEY=XXX
DOMAIN=XXX
BUCKET_NAME=XXX
NODE_ENV=staging

Here's the process.env variable when I console log it:

NODE_ENV: "production"
PUBLIC_URL: ""
WDS_SOCKET_HOST: undefined
WDS_SOCKET_PATH: undefined
WDS_SOCKET_PORT: undefined

I only have one serverless.yml file:

component: [email protected]
name: XXX
app: XXX

inputs:
  src:
    src: ./src
    hook: yarn build
    dist: ./build
  domain: ${env:DOMAIN}
  region: us-west-2
  bucketName: ${env:BUCKET_NAME}

plugins:
  - serverless-dotenv-plugin

Is there a way to inject environment variables under inputs? I know this is possible in the express serverless component like this:

component: [email protected]
...
inputs:
  ...
  env:
     TEST: ${env:TEST}

Any ideas of why this isn't working? Thanks!

from website.

eahefnawy avatar eahefnawy commented on July 25, 2024

@spencer-wegner how are you running deploy? The relevant env var is loaded based on the stage you're deploying to.

If you run sls deploy, this loads .env file

If you run sls deploy --stage prod, this loads .env.prod file

if you run sls deploy --stage dev, this loads .env.dev file

Other than that, you seem to be referencing the env vars correctly in the serverless.yml file. You just don't need that serverless-dotenv-plugin. Plugins don't work in components.

from website.

spencer-wegner avatar spencer-wegner commented on July 25, 2024

@eahefnawy I have been running deploy the way you are describing it. I am still unsuccessful however. I am using Create React App for my build process which does not allow developers to manually change the NODE_ENV variable. See here. I think that even if I define a NODE_ENV variable in my .env files it is getting overwritten by CRA.

Let me know if you think setting the NODE_ENV variable should be possible despite using CRA. Otherwise I'm just manually adjusting my configuration file depending on my deployment environment. Thanks!

from website.

eahefnawy avatar eahefnawy commented on July 25, 2024

@Enase absolutely agreed! Assuming we have this feature, could you share with us how your frontend code would typically access these environment variables?

from website.

Enase avatar Enase commented on July 25, 2024

Hi @eahefnawy

I believe you can modify @serverless/platform-client/src/instance.js:186

Current state:

/*
 * Run a "src" hook, if one is specified
 */
const preRunSrcHook = async (src) => {
  if (typeof src === 'object' && src.hook && src.dist) {
    // First run the build hook, if "hook" and "dist" are specified
    const options = { cwd: src.src }
    return new Promise((resolve, reject) => {
      exec(src.hook, options, (err) => {
        if (err) {
          return reject(
            new Error(`Failed running "src.hook": "${src.hook}" due to the following error: "${err.stderr}"
        ${err.stdout}`)
          )
        }
        return resolve(src.dist)
      })
    })
  } else if (typeof src === 'object' && src.src) {
    src = path.resolve(src.src)
  } else if (typeof src === 'string') {
    src = path.resolve(src)
  }
  return src
}

Just add environment to options:

 const options = { cwd: src.src, env: instance.inputs.environment }

from website.

eahefnawy avatar eahefnawy commented on July 25, 2024

@Enase yep that's exactly what I'm thinking. But how would your frontend environment access these env vars?

from website.

Enase avatar Enase commented on July 25, 2024

@eahefnawy

suppose you use webpack build: webpack --config path/to/webpack/config.js

  1. Dotenv
module.exports = {
  ...
  plugins: [
    new Dotenv({
      systemvars: true, // load all the predefined 'process.env' variables which will trump anything local per dotenv specs.
    })
  ]
  ...
};
  1. EnvironmentPlugin
module.exports = {
  ...
  plugins: [
    new webpack.EnvironmentPlugin({
      YOUR_VRIABLE: process.env.YOUR_VRIABLE,
    }),
  ]
  ...
};

I can add more, but at the end it doesn't matter. A way to process it may vary in different implementations.

from website.

eahefnawy avatar eahefnawy commented on July 25, 2024

We've merged a fix. Sorry for the delay here. It took us forever to discuss it internally!

from website.

Enase avatar Enase commented on July 25, 2024

@eahefnawy Could you share any implementation details?

from website.

Enase avatar Enase commented on July 25, 2024

@eahefnawy I understand that fix relates to some internal repo, but I didn't find any related changes in the latest release of platform-client
PS any help very appreciated

from website.

brycelund avatar brycelund commented on July 25, 2024

@eahefnawy Could you link to the relevant docs on what was decided to fix this?

from website.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.