Movatterモバイル変換


[0]ホーム

URL:


Skip to contentSkip to navigationSkip to topbar
Go to the Twilio Docs home page
Twilio Docs

Environment Variables


Environment Variables are key/value pairs that you can add to a specificEnvironment. Use these for storing configuration like API keys rather than hardcoding them into yourFunctions. Environment Variables are encrypted, so they are the preferred way to store API keys, passwords, and any other secrets that your Function needs to use.

They also prove useful because when an Environment Variable is updated, the new value will instantly reflect in subsequent Function executions without the need for deploying new code. This allows you to adjust configurations on the fly without potentially interrupting your service due to deployments.


Setting Environment Variables

setting-environment-variables page anchor

To view and modify the Environment Variables for a givenService, open the Service using theTwilio Console. Once the Functions Editor is open for your Service, in theSettings menu, click onEnvironment Variables.

Environment Variables UI.

The resulting UI allows you to add, remove, and update Environment Variables.

Additionally, theAdd my Twilio Credentials (ACCOUNT_SID) and (AUTH_TOKEN) to ENV checkbox allows you to choose if you would like for your ACCOUNT SID and AUTH TOKEN to be automatically added to your Function's context. This means both of these values will be accessible as Environment Variables fromcontext, and also that callingcontext.getTwilioClient() will return an initialized Twilio REST client for making calls to Twilio's API.

(information)

Info

If you're using the Serverless Toolkit, you will insteadset your EnvironmentVariables using .envfiles.

Editing Environment Variables across Environments

editing-environment-variables-across-environments page anchor

If you're using multiple Environments in your application, such as dev, stage, and production, it's common to have the same Environment Variables present in each Environment, but with different values so that each version of your application is connecting to the appropriate resources. These could be various API keys with different levels of access or rate limits for the same service, credentials for different versions of your database, and more.

Using the Console UI, you can switch between which Environment Variables you are adjusting by clicking on your application URL, directly above theDeploy All button. This will render a menu showing your various Environments, and selecting one will put you in the context of that Environment.

Environment Selector.

Any modifications to Environment Variables that follow will only apply to the selected Environment and not affect any others.

(information)

Info

If you're developing using the Serverless Toolkit, check out the specificdocumentation onhow to scope environmentvariables.


Consuming Environment Variables

consuming-environment-variables page anchor

Any Environment Variables that have been set will be accessible in your Function as properties of thecontext object by name. For example, if you set an Environment Variable named API_KEY, it can be retrieved ascontext.API_KEY in your Function's code.

Suppose an IVR tree you're designing requires some logic to determine if a branch of your business is open that day based on local temperatures. Using the OpenWeather Weather API and an API Key that you've set to an Environment Variable, you could securely retrieve that key fromcontext.API_KEY and make validated requests for weather data to complete your business logic. You can also store a common support phone number as an Environment Variable to share between your Functions.

1
constaxios=require("axios");
2
constquerystring=require("querystring");
3
4
exports.handler= async(context,event,callback)=>{
5
// Environment Variables can be accessed from the context object
6
constapiKey=context.API_KEY;
7
constsupportNumber=context.SUPPORT_PHONE_NUMBER;
8
9
// Query parameters and the request body can be accessed
10
// from the event object
11
constcity=event.city||"Seattle";
12
13
// The Weather API accepts the city and apiKey as query parameters
14
constquery=querystring.stringify({ q: city, appid: apiKey });
15
// Make our OpenWeather API request, and be sure to await it!
16
const{data}= awaitaxios.get(
17
`https://api.openweathermap.org/data/2.5/weather?${query}`
18
);
19
// Do some math to convert the returned temperature from Kelvin to F
20
consttempInFahrenheit=(data.main.temp-273.15)*1.8+32;
21
// If its too hot, relay this information and the support number
22
if(tempInFahrenheit>=100) {
23
returncallback(null, {
24
isOpen:false,
25
message:
26
"Due to extreme temperatures and to protect the health "+
27
"of our employees, we're closed today. If you'd like to "+
28
`speak to our support team, please call ${supportNumber}`,
29
});
30
}
31
// Otherwise, business as usual
32
returncallback(null, { isOpen:true, message:"We're open!"});
33
};

Default Environment Variables

default-environment-variables page anchor

Thecontext object provides you with several Environment Variables by default:

PropertyTypeDescription
ACCOUNT_SIDstring|nullIf you have chosen to include your account credentials in your Function, this will return the SID identifying the Account that owns this Function. If you have not chosen to include account credentials in your Function, this value will benull.
AUTH_TOKENstring|nullIf you have chosen to include your account credentials in your Function, this will return the Auth Token associated with the owning Account. If you have not chosen to include account credentials in your Function, this value will benull.
DOMAIN_NAMEstringThe Domain that is currently serving your Twilio Function.
PATHstringThe path of Twilio Function that is currently being executed.
SERVICE_SIDstringThe SID of theService which the current Function is contained in.
ENVIRONMENT_SIDstringThe SID of theEnvironment which the current Function is hosted in.
(warning)

Warning

For a small number of customers,SERVICE_SID andENVIRONMENT_SID are not enabled due to the combined size of environment variables in use being too high and approaching the allowed limit of3kb. In this case, these variables will returnundefined.

If you believe you are affected by this issue and wish to enable these variables, please reach out to our support team for assistance.


There are limitations on the size of individual Environment Variables depending on your method of deployment. A variable can be no longer than:

  • 255 characters if set using the current V2 Console
  • 150 characters if set using the legacy, Functions(Classic) Console
  • 450 bytes if set using the Serverless Toolkit or the Serverless API

Additionally, there is a maximum limit of approximately3kb on the combined size of your Environment Variables after they have been JSON encoded.

(error)

Danger

If any Environment Variable exceeds the individual limit or all Variablescombined exceed the maximum limit, then your deployments will fail until yourVariables have been resized.

Storing large credentials

storing-large-credentials page anchor

If you must store an extremely long API key or other credential, such as an RSA key, which will cause you to exceed these limits, we suggest that you instead store the value in aprivate Asset and ingest it in your code using theRuntime.getAssets helper.

Given these constraints and a large RSA key that you need to store securely, you could store the text of the key in an Asset namedcredentials.json, and set the Asset's Privacy toprivate.

1
{
2
"myRsaKey":"xxxxxx..."
3
}

You could then access the RSA key (or any other stored credentials) in your Function using this code pattern.

1
exports.handler=(context,event,callback)=>{
2
// The open method returns the file's contents assuming utf8 encoding.
3
// Use JSON.parse to parse the file back into a JavaScript object
4
constcredentials=JSON.parse(
5
Runtime.getAssets()["/credentials.json"].open()
6
);
7
8
// Reference the key from the credentials object
9
const{myRsaKey}=credentials;
10
11
// Perform any API calls that require this key!...
12
};

[8]ページ先頭

©2009-2025 Movatter.jp