Skip to content

Commit 368b099

Browse files
authored
Merge pull request #298 from amirkaws/parameters-example
2 parents f51155a + 39be981 commit 368b099

19 files changed

+2354
-0
lines changed

examples/Parameters/.gitignore

Lines changed: 638 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio Version 16
4+
VisualStudioVersion = 16.0.30114.105
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{DF119D9D-FC8B-4ED3-9153-BB15250F29D0}") = "HelloWorld", "src\HelloWorld\HelloWorld.csproj", "{224EC34E-A942-4FD0-8EC2-9C4526066611}"
7+
EndProject
8+
Project("{DF119D9D-FC8B-4ED3-9153-BB15250F29D0}") = "HelloWorld.Tests", "test\HelloWorld.Test\HelloWorld.Tests.csproj", "{C22D9998-9C36-4AC3-B00E-DEC8491B1805}"
9+
EndProject
10+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HelloWorld.Cfn", "cfn\HelloWorld.Cfn\HelloWorld.Cfn.csproj", "{4923974C-33DA-4C80-B0EF-E3E18587351D}"
11+
EndProject
12+
Global
13+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
14+
Debug|Any CPU = Debug|Any CPU
15+
Release|Any CPU = Release|Any CPU
16+
EndGlobalSection
17+
GlobalSection(SolutionProperties) = preSolution
18+
HideSolutionNode = FALSE
19+
EndGlobalSection
20+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
21+
{224EC34E-A942-4FD0-8EC2-9C4526066611}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
22+
{224EC34E-A942-4FD0-8EC2-9C4526066611}.Debug|Any CPU.Build.0 = Debug|Any CPU
23+
{224EC34E-A942-4FD0-8EC2-9C4526066611}.Release|Any CPU.ActiveCfg = Release|Any CPU
24+
{224EC34E-A942-4FD0-8EC2-9C4526066611}.Release|Any CPU.Build.0 = Release|Any CPU
25+
{C22D9998-9C36-4AC3-B00E-DEC8491B1805}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
26+
{C22D9998-9C36-4AC3-B00E-DEC8491B1805}.Debug|Any CPU.Build.0 = Debug|Any CPU
27+
{C22D9998-9C36-4AC3-B00E-DEC8491B1805}.Release|Any CPU.ActiveCfg = Release|Any CPU
28+
{C22D9998-9C36-4AC3-B00E-DEC8491B1805}.Release|Any CPU.Build.0 = Release|Any CPU
29+
{4923974C-33DA-4C80-B0EF-E3E18587351D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
30+
{4923974C-33DA-4C80-B0EF-E3E18587351D}.Debug|Any CPU.Build.0 = Debug|Any CPU
31+
{4923974C-33DA-4C80-B0EF-E3E18587351D}.Release|Any CPU.ActiveCfg = Release|Any CPU
32+
{4923974C-33DA-4C80-B0EF-E3E18587351D}.Release|Any CPU.Build.0 = Release|Any CPU
33+
EndGlobalSection
34+
EndGlobal

examples/Parameters/README.md

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
# Powertools for AWS Lambda (.NET) - Parameters Example
2+
3+
This project contains source code and supporting files for a serverless application that you can deploy with the AWS Serverless Application Model Command Line Interface (AWS SAM CLI). It includes the following files and folders.
4+
5+
* src - Code for the application's Lambda function and Project Dockerfile.
6+
* events - Invocation events that you can use to invoke the function.
7+
* test - Unit tests for the application code.
8+
* template.yaml - A template that defines the application's AWS resources.
9+
10+
The application uses several AWS resources, including Lambda functions and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code.
11+
12+
If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit. The AWS Toolkit is an open source plug-in for popular IDEs that uses the AWS SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds a simplified step-through debugging experience for Lambda function code. See the following links to get started.
13+
14+
* [Visual Studio Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html)
15+
* [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html)
16+
* [Rider](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
17+
18+
## Deploy the sample application
19+
20+
The AWS SAM CLI is an extension of the AWS Command Line Interface (AWS CLI) that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API.
21+
22+
To use the AWS SAM CLI, you need the following tools.
23+
24+
* AWS SAM CLI - [Install the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)
25+
* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community)
26+
27+
You will need the following for local testing.
28+
* .NET 6.0 - [Install .NET 6.0](https://www.microsoft.com/net/download)
29+
30+
To build and deploy your application for the first time, run the following in your shell. Make sure the `template.yaml` file is in your current directory:
31+
32+
```bash
33+
sam build
34+
sam deploy --guided
35+
```
36+
37+
The first command will build a docker image from a Dockerfile and then copy the source of your application inside the Docker image. The second command will package and deploy your application to AWS, with a series of prompts:
38+
39+
* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name.
40+
* **AWS Region**: The AWS region you want to deploy your app to.
41+
* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes.
42+
* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command.
43+
* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application.
44+
45+
You can find your API Gateway Endpoint URL in the output values displayed after deployment.
46+
47+
This application creates some additional AWS resources. You can find them by navigating to their relevant AWS services in [AWS Management Console](console.aws.amazon.com) after deployment.
48+
49+
| Resource Type | AWS Service | Resource Name |
50+
| -------- | ------- | ------- |
51+
| Parameter | AWS Systems Manager Parameter Store | `/powertools-parameters-example/path/prefix/parameter` |
52+
| Parameter | AWS Systems Manager Parameter Store | `/powertools-parameters-example/path/prefix/other-parameter` |
53+
| Secret | AWS Secrets Manager | `PowertoolsParametersExampleSecret` |
54+
| Table | Amazon DynamoDB | `PowertoolsParametersExampleSingle` |
55+
| Table | Amazon DynamoDB | `PowertoolsParametersExampleMultiple` |
56+
57+
58+
## Use the AWS SAM CLI to build and test locally
59+
60+
Build your application with the `sam build` command.
61+
62+
```bash
63+
Parameters$ sam build
64+
```
65+
66+
The AWS SAM CLI builds a docker image from a Dockerfile and then installs dependencies defined in `src/HelloWorld.csproj` inside the docker image. The processed template file is saved in the `.aws-sam/build` folder.
67+
68+
Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project.
69+
70+
Run functions locally and invoke them with the `sam local invoke` command.
71+
72+
```bash
73+
Parameters$ sam local invoke HelloWorldFunction --event events/event.json
74+
```
75+
76+
The AWS SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000.
77+
78+
```bash
79+
Parameters$ sam local start-api
80+
Parameters$ curl http://localhost:3000/hello
81+
```
82+
83+
The AWS SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The `Events` property on each function's definition includes the route and method for each path.
84+
85+
```yaml
86+
Events:
87+
HelloWorld:
88+
Type: Api
89+
Properties:
90+
Path: /hello
91+
Method: get
92+
```
93+
94+
## Add a resource to your application
95+
96+
The application template uses AWS Serverless Application Model (AWS SAM) to define application resources. AWS SAM is an extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources such as functions, triggers, and APIs. For resources not included in [the AWS SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use standard [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) resource types.
97+
98+
## Fetch, tail, and filter Lambda function logs
99+
100+
To simplify troubleshooting, AWS SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug.
101+
102+
`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM.
103+
104+
```bash
105+
Parameters$ sam logs -n HelloWorldFunction --stack-name Parameters --tail
106+
```
107+
108+
You can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html).
109+
110+
## Unit tests
111+
112+
Tests are defined in the `test` folder in this project.
113+
114+
```bash
115+
Parameters$ dotnet test test/HelloWorld.Test
116+
```
117+
118+
## Cleanup
119+
120+
To delete the sample application that you created, use the AWS SAM CLI. Assuming you used your project name for the stack name, you can run the following:
121+
122+
```bash
123+
Parameters$ sam delete
124+
```
125+
126+
## Resources
127+
128+
See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the AWS SAM CLI, and serverless application concepts.
129+
130+
Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/)
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License").
5+
* You may not use this file except in compliance with the License.
6+
* A copy of the License is located at
7+
*
8+
* http://aws.amazon.com/apache2.0
9+
*
10+
* or in the "license" file accompanying this file. This file is distributed
11+
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12+
* express or implied. See the License for the specific language governing
13+
* permissions and limitations under the License.
14+
*/
15+
16+
using System;
17+
18+
namespace HelloWorld.Cfn;
19+
20+
/// <summary>
21+
/// CloudFormation Custom Resource Request
22+
/// </summary>
23+
[Serializable]
24+
public class CfnRequest
25+
{
26+
public string? RequestType { get; set; }
27+
28+
public string? ResponseURL { get; set; }
29+
30+
public string? StackId { get; set; }
31+
32+
public string? RequestId { get; set; }
33+
34+
public string? ResourceType { get; set; }
35+
36+
public string? LogicalResourceId { get; set; }
37+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License").
5+
* You may not use this file except in compliance with the License.
6+
* A copy of the License is located at
7+
*
8+
* http://aws.amazon.com/apache2.0
9+
*
10+
* or in the "license" file accompanying this file. This file is distributed
11+
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12+
* express or implied. See the License for the specific language governing
13+
* permissions and limitations under the License.
14+
*/
15+
16+
using System;
17+
18+
namespace HelloWorld.Cfn;
19+
20+
/// <summary>
21+
/// CloudFormation Custom Resource Response
22+
/// </summary>
23+
[Serializable]
24+
public class CfnResponse
25+
{
26+
public string? Status { get; set; }
27+
28+
public string? Reason { get; set; }
29+
30+
public string? PhysicalResourceId { get; set; }
31+
32+
public string? StackId { get; set; }
33+
34+
public string? RequestId { get; set; }
35+
36+
public string? LogicalResourceId { get; set; }
37+
38+
public bool NoEcho { get; set; }
39+
}
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
/*
2+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License").
5+
* You may not use this file except in compliance with the License.
6+
* A copy of the License is located at
7+
*
8+
* http://aws.amazon.com/apache2.0
9+
*
10+
* or in the "license" file accompanying this file. This file is distributed
11+
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12+
* express or implied. See the License for the specific language governing
13+
* permissions and limitations under the License.
14+
*/
15+
16+
using System;
17+
using System.Collections.Generic;
18+
using System.Net;
19+
using System.Text;
20+
using System.Text.Json;
21+
using System.Threading.Tasks;
22+
using Amazon.DynamoDBv2;
23+
using Amazon.DynamoDBv2.Model;
24+
using Amazon.Lambda.Core;
25+
using Amazon.Lambda.Serialization.SystemTextJson;
26+
27+
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
28+
[assembly: LambdaSerializer(typeof(DefaultLambdaJsonSerializer))]
29+
30+
namespace HelloWorld.Cfn;
31+
32+
public class Function
33+
{
34+
public async Task FunctionHandler(object cfnRequest, ILambdaContext context)
35+
{
36+
var request = JsonSerializer.Deserialize<CfnRequest>(cfnRequest.ToString()!);
37+
Console.Write(JsonSerializer.Serialize(request));
38+
39+
var response = new CfnResponse
40+
{
41+
StackId = request!.StackId,
42+
RequestId = request.RequestId,
43+
LogicalResourceId = request.LogicalResourceId,
44+
PhysicalResourceId = "powertools_parameters_custom_physical_resource_id",
45+
Status = "SUCCESS",
46+
Reason = string.Empty,
47+
NoEcho = false
48+
};
49+
50+
try
51+
{
52+
switch (request.RequestType!.ToLower())
53+
{
54+
case "create":
55+
LambdaLogger.Log("Received Create request");
56+
await InsertSingleParameterForDynamoDBProvider().ConfigureAwait(false);
57+
await InsertMultipleParametersForDynamoDBProvider().ConfigureAwait(false);
58+
break;
59+
}
60+
}
61+
catch (Exception ex)
62+
{
63+
LambdaLogger.Log($"Error:{ex.Message}");
64+
response.Status = "FAILED";
65+
response.Reason = ex.Message;
66+
}
67+
68+
LambdaLogger.Log($"Sending response to {request.ResponseURL} ");
69+
SendResponse(request.ResponseURL!, response);
70+
LambdaLogger.Log("Finished");
71+
}
72+
73+
private static void SendResponse(string url, CfnResponse cfnResponse)
74+
{
75+
var json = JsonSerializer.Serialize(cfnResponse);
76+
var byteArray = Encoding.UTF8.GetBytes(json);
77+
78+
LambdaLogger.Log($"trying to upload json {json}");
79+
80+
var httpRequest = WebRequest.Create(url) as HttpWebRequest;
81+
httpRequest.Method = "PUT";
82+
//If ContentType is set to anything but "" your upload will fail
83+
httpRequest.ContentType = "";
84+
httpRequest.ContentLength = byteArray.Length;
85+
86+
using (var datastream = httpRequest.GetRequestStream())
87+
datastream.Write(byteArray, 0, byteArray.Length);
88+
var result = httpRequest.GetResponse() as HttpWebResponse;
89+
90+
LambdaLogger.Log($"Result of upload is {result.StatusCode}");
91+
}
92+
93+
private async Task InsertSingleParameterForDynamoDBProvider()
94+
{
95+
LambdaLogger.Log($"Inserting single parameter for DynamoDBProvider...");
96+
97+
var client = new AmazonDynamoDBClient();
98+
99+
// Get DynamoDB partition key
100+
var tableName = Environment.GetEnvironmentVariable(EnvironmentVariableNames.DynamoDBSingleParameterTableName) ??
101+
"";
102+
103+
// Get DynamoDB partition key
104+
var hashKey = Environment.GetEnvironmentVariable(EnvironmentVariableNames.DynamoDBSingleParameterId) ?? "";
105+
106+
var request = new PutItemRequest
107+
{
108+
TableName = tableName,
109+
Item = new Dictionary<string, AttributeValue>()
110+
{
111+
{ "id", new AttributeValue { S = hashKey } },
112+
{ "value", new AttributeValue { S = "my-value" } }
113+
}
114+
};
115+
116+
await client.PutItemAsync(request).ConfigureAwait(false);
117+
}
118+
119+
private async Task InsertMultipleParametersForDynamoDBProvider()
120+
{
121+
LambdaLogger.Log($"Inserting multiple parameters for DynamoDBProvider...");
122+
123+
var client = new AmazonDynamoDBClient();
124+
125+
// Get DynamoDB partition key
126+
var tableName =
127+
Environment.GetEnvironmentVariable(EnvironmentVariableNames.DynamoDBMultipleParametersTableName) ?? "";
128+
129+
// Get DynamoDB partition key
130+
var hashKey =
131+
Environment.GetEnvironmentVariable(EnvironmentVariableNames.DynamoDBMultipleParametersParameterId) ?? "";
132+
133+
for (var i = 1; i <= 3; i++)
134+
{
135+
var request = new PutItemRequest
136+
{
137+
TableName = tableName,
138+
Item = new Dictionary<string, AttributeValue>()
139+
{
140+
{ "id", new AttributeValue { S = hashKey } },
141+
{ "sk", new AttributeValue { S = $"param-{i}" } },
142+
{ "value", new AttributeValue { S = $"my-value-{i}" } }
143+
}
144+
};
145+
146+
await client.PutItemAsync(request).ConfigureAwait(false);
147+
}
148+
}
149+
}

0 commit comments

Comments
 (0)