In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "introduction of Serverless multi-environment configuration scheme". Friends who are interested may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn the introduction of Serverless multi-environment configuration scheme.
I believe that after reading the previous articles on Serverless Component, my friends have already experienced the traversal it brings to our development. But in fact, in our daily development project, it is not just a project deployment, but also development, joint debugging, testing, pre-release, formal environment and other keywords in our agile development process. So there are small partners have doubts, my business development is finished, how to manage the configuration of different environments? For example, how to switch between the database configuration of the test environment and the formal environment? So I introduced it and wrote this article to study and discuss with you.
After reading this article, you will learn:
Principles of Serverless Component deployment
Basic use of dotenv module
How to switch multi-environment configuration based on dotenv
How to refine the general configuration in serverless.yml
Serverless Component
Theory guides practice
Before introducing the method, we need to give a brief introduction to the principle of Serverless Component deployment. What happens when we configure the project in the serverless.yml file and execute the sls-- debug command?
The core steps are as follows:
1. Initialize context: including analyzing the component dependency tree, injecting environment variables through dotenv, etc. two。 Install dependent component module: different from `npm install`, serverless component downloads and decompresses the npm module specified by `installent` to `~ / .serverless/components/registry/npm/@serverless/xxx@ x.x.x`. 3. Execute the `default` function of the component module: this default function is the deployment logic code provided by the developer, such as uploading the packaged code to cos and then deploying it to scf.
This article only needs to be concerned with the injection of environment variables in the first step.
You can find that the Serverless Framework deployment command will help us inject the environment variables in the .env file into the deployment process by default, which is why we need to create a .env file with the following contents when using Tencent Cloud components:
TENCENT_SECRET_ID=xxxTENCENT_SECRET_KEY=xxx
Note: of course, Tencent Cloud components all support one-click login, if you do not want to configure .env file. Isn't it cool ~
Based on this, we can do a lot of things with .env files. For example, in serverless.yml, you can get the injected environment variables in the form of ${env.xxx}.
Dotenv module
Dotenv is a module that can inject environment variables into process.env through .env files.
It is easy to use. Install npm install dotenv-save first, and then introduce it into your project entry file:
Require ("dotenv") .config (); manage multiple environment configurations
Having said so much, I finally come to the main topic of this article. Here, taking the tencent-koa component as an example, let's initialize our project first:
# this command will specify the github directory containing `serverless.yml` as the project template and copy it to the local $serverless create-template-url https://github.com/yugasun/tencent-serverless-demo/tree/master/serverless-env# installation depends on $cd severless-env & & npm install
Then create two new configuration files, which are:
# .env.test file content USER_NAME=yugasun_testUSER_EMAIL=yugasun_test@163.com# .env.release file content USER_NAME=yugasun_releaseUSER_EMAIL=yugasun_release@163.com
Then create a new entry file app.js:
Const dotenv = require ("dotenv"); const Koa = require ("koa"); const KoaRouter = require ("koa-router"); const {CODE_ENV} = process.env;dotenv.config ({path: `${_ dirname} / .env. ${CODE_ENV}`}); const app = new Koa (); const router = new KoaRouter (); router.get ("/", async ctx = > {ctx.body = {name: process.env.USER_NAME, email: process.env.USER_EMAIL}) }); app.use (router.allowedMethods ()) .use (router.routes ()); / / don't forget to export module.modules = app
This is a simple demo that reads different .env.xxx configurations through the environment variable CODE_ENV injected by the cloud function to switch configurations between different environments. The core code is as follows:
Const {CODE_ENV} = process.env;dotenv.config ({path: `${_ dirname} / .env. ${CODE_ENV}`})
Note: here the config function of dotenv can specify path as the target .env file path.
So you only need to configure an environment variable CODE_ENV for the cloud function. Next, let's write the serverless.yml file:
# current running environment CODE_ENV: testMyExpress: component: "@ serverless/tencent-koa" inputs: region: ap-guangzhou functionName: express-function code:. / functionConf: timeout: 10 memorySize: 128 environment: variables: CODE_ENV: ${CODE_ENV} apigatewayConf: protocols:-http-https environment: ${CODE_ENV}
I'm sure you all know that you can configure environment variables through functionConf.environment.variables. Not only the environment variables of the cloud function are configured, but also apigatewayConf.environment is configured to distinguish the test and release environment of the API gateway.
Tip: you can define the public variable CODE_ENV at the top of the yml file and then reference the variable in the form of ${CODE_ENV}.
Then execute the deployment command sls-debug. After the deployment is successful, visit the url link that has been created successfully, and you can see the result of the configured environment variables:
{"name": "yugasun_test", "email": "yugasun_test@163.com"}
When we are finished, we need to deploy to the release environment, just change the CODE_ENV value in serverless.yml to release, and then redeploy.
Configuration Optimization 1
Careful partners will find that although successfully deployed cloud functions can successfully read different environment configurations, each deployment will upload .env.test and .env.release configuration files at the same time. Sometimes we don't want to expose the configuration of the production environment in the test environment, so we need to upload only the corresponding configuration file each time we deploy. To do this, simply add exclude and incldue configurations to the serverless.yml configuration file:
CODE_ENV: releaseMyExpress: component: "@ serverless/tencent-koa" inputs: region: ap-guangzhou functionName: express-function code:. / exclude:-.env.release-.env.test include:-.e nv.$ {CODE_ENV} functionConf: timeout: 10 memorySize: 128 environment: variables: CODE_ENV: ${CODE_ENV} ApigatewayConf: protocols:-http-https environment: ${CODE_ENV}
Here, all configuration files are ignored through the exclude configuration, and then the specified configuration files are included through include. We do this because we specify the code field as. /-the project root, so all files in the project root are uploaded by default.
Configuration Optimization 2
Of course, you can also write any fixed parameters in serverless.yml to a .env file, such as the CODE_ENV variable here, and then reference it through ${env.CODE_ENV}. For example, we write CODE_ENV to .env:
CODE_ENV=release
Then modify the serverless.yml configuration:
MyExpress: component: "@ serverless/tencent-koa" inputs: region: ap-guangzhou functionName: express-function code:. / exclude:-.env.release-.env.test include:-.env. ${env.CODE_ENV} functionConf: timeout: 10 memorySize: 128 environment: variables: CODE_ENV: ${env.CODE_ENV} ApigatewayConf: protocols:-http-https environment: ${env.CODE_ENV}
It is important to note that the drawback of .env files is that objects and arrays cannot be defined. However, for private configurations, it is more appropriate to put it in .env, so that deployment can be ignored based on files.
Configuration Optimization 3
When you need to deploy the same business code to different regions, but the function parameter configuration is the same as the API gateway configuration, how to configure it? The general configuration can also be extracted here, as follows:
# global configCODE_ENV: release# function configFUNC_CONF: name: express-function memorySize: 128timeout: 10 environment: variables: CODE_ENV: ${CODE_ENV} # apigw configAPI_CONF: protocols:-http-https environment: ${CODE_ENV} # guangzhou serviceMyExpressGZ: component: "@ serverless/tencent-koa" inputs: region: ap-guangzhou functionName: ${FUNC_CONF.name} code:. / exclude: -.env.release-.env.test include:-.env. ${CODE_ENV} functionConf: ${FUNC_CONF} apigatewayConf: ${API_CONF} # beijing serviceMyExpressBJ: component: "@ serverless/tencent-koa" inputs: region: ap-beijing functionName: ${FUNC_CONF.name} code:. / exclude:-.env.release-.env.test include :-.env. ${CODE_ENV} functionConf: ${FUNC_CONF} apigatewayConf: ${API_CONF} how to choose a configuration scheme
This paper introduces two schemes:
Configure through .env
By defining variables in serverless.yml
They can all define global variables, so how to choose to use them in actual development?
Note: variables defined by serverless.yml, or automatically injected in .env, can only be obtained after executing the sls-- debug command. The actual deployment of successful code requires that the .env file be specified through the dotenv module to manually load the injection. Of course, it's OK if you can also parse the serverless.yml file to get the variables you need.
Usually I put the configuration at the time of deployment in serverless.yml and the business-related configuration in the .env file. Of course, this is just a personal suggestion, and how to configure it depends on your personal habits.
Other languages
Although this article only describes how to manage multi-environment configuration in a Nodejs project, other languages basically implement the dotenv module, so this approach is common, such as Python's python-dotenv module, which is basically similar to use:
# settings.pyfrom dotenv import load_dotenvfrom pathlib import Path # python3 onlyenv_path = Path ('.') /. Env.test'load_dotenv (dotenv_path=env_path) so far, I believe you have a better understanding of "introduction to Serverless multi-environment configuration". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.