Metadata
The Metadata utility allows you to fetch data from the AWS Lambda Metadata Endpoint (LMDS). This can be useful for retrieving information about the Lambda function, such as the Availability Zone ID.
Getting started¶
Installation¶
Add the library to your project:
1 | |
Usage¶
You can fetch data from the LMDS using the getMetadata function. For example, to retrieve the Availability Zone ID:
Tip
Metadata is cached for the duration of the Lambda execution, so subsequent calls to getMetadata will return the cached data.
1 2 3 4 5 6 7 8 9 10 | |
Available metadata¶
| Property | Type | Description |
|---|---|---|
AvailabilityZoneID |
string |
The AZ where the function is running (e.g., use1-az1) |
Testing your code¶
The metadata endpoint is not available during local development or testing. To ease testing, the getMetadata function automatically detects when it's running in a non-Lambda environment and returns an empty object. This allows you to write tests without needing to mock the LMDS responses.
If instead you want to mock specific metadata values for testing purposes, you can do so by setting environment variables that correspond to the metadata endpoint and authentication token, as well as mocking the fetch function to return the desired metadata. Here's an example of how to do this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | |
We also expose a clearMetadataCache function that can be used to clear the cached metadata, allowing you to test different metadata values within the same execution context.