问题
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:
- In the IAM policy of the function (allowing access to the bucket).
- 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