How Can I Reference Environment Variables in serverless.ts? - serverless

I'm using serverless-ssm-fetch in my serverless.ts file, which resolves many of the variables that are environment specific. This works great when I'm referencing these variables in my code, however, I have two values in my serverless.ts file itself that I'd like to draw from SSM Parameter Store. Below is my serverless.ts file, and what I'm trying to do to pull in lambda-security-group-ids and lambda-subnet-ids is working, but I'm not sure how to reference them within the serverless.ts file. Does anyone know how to do this?
import type { AWS } from '#serverless/typescript';
import importFacility from '#functions/ImportFacility';
import ProcessEvent from '#functions/ProcessEvent';
const serverlessConfiguration: AWS = {
service: 'myservice',
frameworkVersion: '2',
custom: {
webpack: {
webpackConfig: './webpack.config.js',
includeModules: true,
},
bundle: {
ignorePackages: ['pg-native']
},
serverlessSsmFetch: {
DB_Host: 'database-host~true',
PORT: 'serverless-database-port~true',
DB_NAME: 'clinical-database-name~true',
DB_USER_NAME: 'database-username~true',
DB_PASSWORD: 'database-password~true',
AWS_ACCESS_KEY: 'serverless-access-key-id~true',
AWS_SECRECT_KEY: 'serverless-access-key-secret~true',
LAMBDA_SECURITY_GROUP_IDS: 'lambda-security-group-ids~true', // WANT TO REFERENCE
LAMBDA_SUBNET_IDS: 'lambda-subnet-ids~true' // WANT TO REFERENCE
}
},
plugins: ['serverless-webpack', 'serverless-ssm-fetch'],
provider: {
name: 'aws',
runtime: 'nodejs14.x',
apiGateway: {
minimumCompressionSize: 1024,
shouldStartNameWithService: true,
},
environment: {
AWS_NODEJS_CONNECTION_REUSE_ENABLED: '1'
},
lambdaHashingVersion: '20201221',
vpc: {
securityGroupIds: [`${process.env.LAMBDA_SECURITY_GROUP_IDS}`], // NOT WORKING
subnetIds: [`${process.env.LAMBDA_SUBNET_IDS}`] // NOT WORKING
}
},
functions: { importFacility, ProcessEvent },
};
module.exports = serverlessConfiguration;

For anyone wondering juste had the issue
the syntax :
vpc: {
securityGroupIds: ['${ssm:${self:custom.serverlessSsmFetch.LAMBDA_SECURITY_GROUP_IDS}}'],
subnetIds: ['${ssm:${self:custom.serverlessSsmFetch.LAMBDA_SUBNET_IDS}}]
}
worked for me.
As far as I understand you have to use the syntax as it would have been rendered while using serverless.yml template

Related

How to get Vite environment variables in tailwind.config.cjs file

I can't figure out how I can grab the specific Vite environment variables in the tailwind.config.cjs file.
.env.development
VITE_TAILWIND_PRESET = preset_one
tailwind.config.cjs
/** #type {import('tailwindcss').Config} */
const presetFiles = {
present_one: './src/styles/presets/one.js',
present_two: './src/styles/presets/two.js',
}
console.log(import.meta.env)
console.log(import.meta.env.VITE_TAILWIND_PRESET)
module.exports = {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [
require('#tailwindcss/forms'),
],
}
The above code throws the error:
console.log(import.meta.env): [vite] Internal server error: [postcss] Unexpected token (7:18)
If I change the code to console.log(process.env) I get all the environment variables except the VITE ones that I've added to the .env.development file.
To be clear, there is nothing wrong with the .env.development file. In my vite.config.js file the file is loaded correctly using
import { defineConfig, loadEnv } from 'vite';
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd())
...

How to use PM2 Process Manager with SvelteKit

I am trying to manage my SvelteKit build with PM2 (Process Manager) — my problem is that I can't succesfully inject a .env-file using an ecosystem.config.cjs. My files currently look like this:
.env.production
PORT=3000
The only changing thing in both configs is at:
env: { }
ecosystem.config.cjs (working fine - app runs on provided port)
module.exports = {
apps: [
{
name: 'my_app',
script: './build/index.js',
watch: false,
ignore_watch: ['database'],
autorestart: true,
// --------------------------------------------------
// if passed directly PORT is being used as expected:
// --------------------------------------------------
env: {
PORT: 3000
}
}
]
};
ecosystem.config.cjs (not working - injected PORT variable is being ignored)
module.exports = {
apps: [
{
name: 'my_app',
script: './build/index.js',
watch: false,
ignore_watch: ['database'],
autorestart: true,
// ----------------------------------------------------
// when I try to inject a .env it's just being ignored:
// ----------------------------------------------------
env: {
ENV_PATH: "./.env.production",
}
}
]
};
Any help is much appreciated and thanks for reading!
Cheers,
Boris
EDIT: Made question a bit more clear + added answer below
The problem wasn't the injection of .env.production, but the PORT environment variable. PORT must be provided directly and can't be part of .env.production (well, it can be but will be ignored).
There's probably another way, but the following works:
ecosystem.config.cjs
module.exports = {
apps: [
{
name: 'my_app',
script: './build/index.js',
watch: false,
ignore_watch: ['database'],
autorestart: true,
// ----------------------------------------------------
// when I try to inject a .env it's just being ignored:
// ----------------------------------------------------
env: {
PORT: 3000,
ENV_PATH: "./.env.production",
}
}
]
};
.env.production
# production
PUBLIC_test=value

cypress 10 is not reading specPattern value after exporting new value to it

I'm facing an issue that i couldn't find a solution for it.
We have updated the version of the cypress from 9.7.0 to 10.2.0 recently, and we used to set the value of testFiles for Docker image using export CYPRESS_TEST_FILES="some files or paths"
Now the testFiles changed to specPattern, and when we use the same method, a new parameter is added to env{} object, and the existing one outside env{} object is still the same.
Now we need a way to change the value of specPattern by exporting the value (we need to change it only in some cases, and not through cypress.config.ts)
cypress.config.ts content:
import { defineConfig } from 'cypress' export default defineConfig({ env: { webBaseUrl: 'http://localhost:4200', highlightColor: '#9ef11a', download_dir: '/cypress/downloads/', }, viewportWidth: 1680, viewportHeight: 1050, defaultCommandTimeout: 15000, reporter: 'mochawesome', video: false, retries: { runMode: 1, openMode: 1, }, reporterOptions: { reportDir: 'cypress/results', overwrite: false, html: false, json: true, }, e2e: { setupNodeEvents(on, config) { return require('./cypress/plugins/index.js')(on, config) }, baseUrl: 'https://localhost', specPattern: 'cypress/e2e/**/*.cy.ts', }, })
i tired:
export CYPRESS_specPattern="cypress/e2e/**/*.spec.ts"
then run cypress:
in the settings are i got the following:
and this is the other specPattern value
and it's clear that it's taking the second one into consideration
any suggestions?

How to pass environment variables to a front-end web application in nginx?

I am using docker-compose with an image made by someone else and I would like to use environment variables to assign it dynamically
docker-compose.yml
version: "3.7"
services:
appfronted2:
image: trafex/alpine-nginx-php7
container_name: fronted2
ports:
- "80:8080"
volumes:
- ./fronted2:/var/www/html
environment:
- HOST_BACKEND=172.99.0.11
- PORT_BACKEND=4000
networks:
tesis:
ipv4_address: 172.99.0.13
and this is my javascript where I would like to get the variables but I can't get those variables
api.js
const HOST = process.env.HOST_BACKEND || "127.0.0.1"
const PORT = process.env.PORT_BACKEND || "4000"
const URL_API = `http://${HOST}:${PORT}/api`
You are using nginx web server container to serve your html and JS files. The web server serves these files to browser as they are. This is different from using npm start where Node engine serves the HTML and JS files dynamically.
When your JS file runs on client browser, there's no variable called process.env.
Going over comments for following issue in Create React app might help you understand more:
https://github.com/facebook/create-react-app/issues/2353
If you don't have more environment variables, simplest solution would be to use window.location.hostname and prepare or select the API url accordingly.
app-config.js
let backendHost;
const hostname = window && window.location && window.location.hostname;
if(hostname === 'whatsgoodonmenu.com') {
backendHost = 'https://api.whatsgoodonmenu.com';
} else {
backendHost = 'http://localhost:8080';
}
export const API_ROOT = `${backendHost}`;
Using in component
import React from "react"
import {API_ROOT} from './app-config'
export default class UserCount extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null,
};
}
componentDidMount() {
fetch(`${API_ROOT}/count`)
.then(response => response.json())
.then(data => this.setState({ data }));
}
render(){
return(
<label>Total visits: {this.state.data}</label>
);
}
}

how to share rollup config files

I have 2 rollup config files which has some common parts and uncommon parts:
// rollup.config.umd.js
export config {
external: ['invariant', 'lodash'],
globals: {
invariant: 'invariant'
},
input: 'src/index.js',
name: 'my.comp',
output: {
file: 'my.comp.umd.js'
format: 'umd'
}...
and another file
// rollup.config.esm5.js
export config {
external: ['invariant', 'lodash'],
globals: {
invariant: 'invariant'
},
input: 'src/index.js',
name: 'my.comp',
output: {
file: 'my.comp.es5.js'
format: 'es'
}...
How do I keep these config files DRY ?
Not keeping DRY has following problems e.g. Imagine many external dependencies - if one forgets to add a new dependency in one place we are in trouble.
(I also use some different set of plugins etc and plugin configs but say that is out of scope of this problem.)
Firstly, they're just JavaScript modules, so you can always do this sort of thing:
// rollup.config.common.js
export default {
external: ['invariant', 'lodash'],
globals: {
invariant: 'invariant'
},
input: 'src/index.js',
name: 'my.comp'
};
// rollup.config.esm5.js
import common from './rollup.config.common.js';
export default Object.assign({
output: {
file: 'my.comp.es5.js'
format: 'es'
}
}, common);
// rollup.config.umd.js
import common from './rollup.config.common.js';
export default Object.assign({
output: {
file: 'my.comp.umd.js'
format: 'umd'
}
}, common);
But the real answer here is to combine the two configs into a single one like so:
export default {
external: ['invariant', 'lodash'],
globals: {
invariant: 'invariant'
},
input: 'src/index.js',
name: 'my.comp',
output: [
{
file: 'my.comp.es5.js'
format: 'es'
},
{
file: 'my.comp.umd.js'
format: 'umd'
}
]
};
As well as being simpler and easier to maintain, this will be faster, because Rollup can save doing a lot of the work twice.
If you need to change more than the output option between builds, you can also export an array of configs from a single file (export default [...]).

Resources