如何以 DRY 方式定义变量 [英] How to define variables in a DRY way

查看:57
本文介绍了如何以 DRY 方式定义变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个写入 S3 存储桶的函数.因此,存储桶名称显然是一个变量",不应将其硬编码到函数中(例如,对于 dev 和 prod 可能是不同的存储桶).

现在,如果我希望函数能够访问它,我至少需要在两个地方使用存储桶名称:

  1. 在函数的 IAM 策略中(允许访问存储桶).
  2. 在函数本身中.

对于 #1,我可以使用一个变量,并引用 s-module 中定义的 IAM 策略中的变量(或在 v0.4 中调用的任何内容:).

对于#2,我可以使用环境变量,然后我可以在运行时在函数代码中访问其值.

但我当然不想定义变量两次(一次使用 sls env set,一次在 s-variables 文件中).那不是很干.但是,我没有看到在定义 envar 时引用变量的方法,反之亦然.

如何只在一处定义存储桶名称?

解决方案

截至 Serverless v0.5,这很容易.环境变量处理融合了无服务器项目变量.您以每个阶段每个区域的方式在 _meta/variables/... 中定义项目变量;例如,在 s-variables-dev-useeast1.json 中:

<代码>{"foo_bucket": "com.example.foo-bucket"}

然后,在使用该存储桶的 s-function.json 文件中,您定义函数所需的环境变量...并引用以类似模板的方式项目变量:

环境":{"BUCKET": "${foo_bucket}"}

然后它会像任何其他环境变量一样出现;所以在节点中:

console.log("The Bucket: " + process.env.BUCKET);//打印 "The Bucket: com.example.foo-bucket"

到目前为止,无服务器文档还没有跟上这一变化,但我希望它们很快就会到来.>

Let's say I have function that writes to a S3 bucket. So the bucket name is clearly a "variable" that should not be hard-coded into the function (might be different buckets for dev vs. prod, for example).

Now, I need to use the bucket name in at least two places if I want the function to be able to access it:

  1. In the IAM policy of the function (allowing access to the bucket).
  2. In the function itself.

For #1 I can use a variable, and refer to the variable in the IAM policy defined in s-module (or whatever it's called in v0.4 :).

For #2 I can use an env var, whose value I could then access in the function code during runtime.

But I certainly don't want to have to define the variable twice (once with sls env set and once in the s-variables file). That's not very DRY. However, I don't see a way to refer to variables when defining envars, or vice versa.

How could I define the bucket name in just one place?

解决方案

As of Serverless v0.5, this is pretty easy. Environment variable handling blends Serverless Project Variables. You define the Project variables in _meta/variables/... in a per-stage per-region way; for instance, in s-variables-dev-useast1.json:

{
    "foo_bucket": "com.example.foo-bucket"
}

Then, in the s-function.json file(s) where that bucket is used, you define the environment variables that function needs... and reference the Project Variable in a template-like way:

"environment": {
    "BUCKET": "${foo_bucket}"
}

It will then appear just like any other environment variable; so in Node:

console.log("The Bucket: " + process.env.BUCKET); 
// prints "The Bucket: com.example.foo-bucket"

So far the Serverless docs haven't caught up with this change, but I expect they should soon-ish.

这篇关于如何以 DRY 方式定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆