Accessing AWS Secrets Manager from .NET Lambda Functions, Part 2 - Using Async Code
Download full source code.
Want to talk with other .NET on AWS developers, ask questions, and share what you know? Join us on Slack!
This is part two in a short series on retrieving secrets from AWS Secrets Manager inside Lambda functions.
In the first post, I showed how to create a secret, and deploy a Lambda function that retrieved the secret. It used a synchronous request to Secrets Manager.
In this post, you will do the same as in the first post, but using a fully async Lambda function.
Steps 1, 2, 3
Follow the steps in the previous post to get the tools, create the secret, and create the Lambda function code.
The code in the Function class will be a little different (don’t forget the using statements from the previous post).
Here is the async
version -
1public class Function
2{
3 public async Task<string> FunctionHandler(ILambdaContext context)
4 {
5 string secretName = "my-credentials";
6 string region = "us-east-1";
7
8 var timeout = context.RemainingTime.Subtract(TimeSpan.FromSeconds(3));
9 var cancellationToken = new CancellationTokenSource(timeout);
10
11 return await GetSecretValue(secretName, region, cancellationToken.Token);
12 }
13
14 private async Task<string> GetSecretValue(string secretName, string region, CancellationToken cancellationToken)
15 {
16 IAmazonSecretsManager client = new AmazonSecretsManagerClient(RegionEndpoint.GetBySystemName(region));
17
18 GetSecretValueRequest request = new GetSecretValueRequest(){
19 SecretId = secretName,
20 VersionStage = "AWSCURRENT"
21 };
22
23 try
24 {
25 GetSecretValueResponse response = await client.GetSecretValueAsync(request, cancellationToken);
26 return response.SecretString;
27 }
28 catch (OperationCanceledException oce)
29 {
30 System.Console.WriteLine($"Request timed out, the cancellation token was triggered. {oce.Message}");
31 throw;
32 }
33 catch (Exception ex)
34 {
35 Console.Error.WriteLine("Error: " + ex.Message);
36 throw;
37 }
38 }
39}
Steps 4, 5, 6, 7
Follow the steps in the previous post to deploy the function, invoke it, fix the permissions, and invoke it again.
Download full source code.