How to define variables in a DRY way

让人想犯罪 __ 提交于 2019-12-10 18:49:45

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/35382007/how-to-define-variables-in-a-dry-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!