Skip to content

Commit

Permalink
Revert "Remove go1.x init templates" (aws#490)
Browse files Browse the repository at this point in the history
* Revert "remove go1.x init templates (aws#486)"

This reverts commit e3bdf85.

* Update python3.9/hello-img/README.md

Co-authored-by: Haresh Nasit <[email protected]>

---------

Co-authored-by: Haresh Nasit <[email protected]>
  • Loading branch information
hawflau and hnnasit authored Feb 21, 2024
1 parent 695a2b0 commit 54427ad
Show file tree
Hide file tree
Showing 82 changed files with 2,516 additions and 0 deletions.
Empty file added go1.x/__init__.py
Empty file.
38 changes: 38 additions & 0 deletions go1.x/event-bridge-schema/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Cookiecutter SAM for golang Lambda functions

This is a dynamic [Cookiecutter](https://github.com/audreyr/cookiecutter) template to create a Serverless EventBridge Custom App based on Serverless Application Model (SAM) and Golang.

It is important to note that you should not try to `git clone` this project but use `cookiecutter` CLI instead as ``{{cookiecutter.project_name}}`` will be rendered based on your input and therefore all variables and files will be rendered properly.

This template creates a Serverless Application using a selected EventBridge Schema (selected during sam init interactive workflow), demonstrating the power of event-driven development with Amazon EventBridge.
## Requirements

Install `cookiecutter` command line:

**Pip users**:

* `pip install cookiecutter`

**Homebrew users**:

* `brew install cookiecutter`

**Windows or Pipenv users**:

* `pipenv install cookiecutter`

**NOTE**: [`Pipenv`](https://github.com/pypa/pipenv) is the new and recommended Python packaging tool that works across multiple platforms and makes Windows a first-class citizen.

## Usage

Access this template by running `sam init` and choosing it from the list of available templates


## Credits

* This project has been generated with [Cookiecutter](https://github.com/audreyr/cookiecutter)
* [Bruno Alla's Lambda function template](https://github.com/browniebroke/cookiecutter-lambda-function)

## License

This project is licensed under the terms of the [MIT License with no attribution](/LICENSE)
Empty file.
18 changes: 18 additions & 0 deletions go1.x/event-bridge-schema/cookiecutter.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"project_name": "Your EventBridge Starter app",
"runtime": "go1.x",
"architectures": {
"value": [ "x86_64" ]
},
"function_name": "HelloWorld",
"AWS_Schema_registry": "aws.events",
"AWS_Schema_name": "EC2InstanceStateChangeNotification",
"AWS_Schema_root": "aws.ec2.EC2InstanceStateChangeNotification",
"AWS_Schema_source": "aws.ec2",
"AWS_Schema_detail_type": "EC2 Instance State-change Notification",
"codegen_path": "{{ cookiecutter.project_name }}/{{ cookiecutter.function_name }}/{{ cookiecutter.AWS_Schema_root|lower|replace('.', '/') }}",
"codegen_package_name": "{{ cookiecutter.AWS_Schema_root.lower()[cookiecutter.AWS_Schema_root.rfind(\".\")+1:] }}",
"_copy_without_render": [
".gitignore"
]
}
4 changes: 4 additions & 0 deletions go1.x/event-bridge-schema/requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
cookiecutter==2.3.0
flake8==3.5.0
pytest==3.3.2
pytest-cookies==0.3.0
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.PHONY: build

build:
go mod download github.com/aws/aws-lambda-go
sam build
126 changes: 126 additions & 0 deletions go1.x/event-bridge-schema/{{cookiecutter.project_name}}/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
# {{ cookiecutter.project_name }}

This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders.

- {{cookiecutter.function_name}}/main.go - Code for the application's Lambda function.
- events - Invocation events that you can use to invoke the function.
- {{cookiecutter.function_name}}/main_tests.go - Unit tests for the application code.
- template.yaml - A template that defines the application's AWS resources.


The application uses several AWS resources, including Lambda functions and an EventBridge Rule trigger. 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.

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 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.

* [CLion](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [GoLand](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [IntelliJ](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [WebStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [Rider](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [PhpStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [PyCharm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [RubyMine](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [DataGrip](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [VS Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html)
* [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html)


## Deploy the sample application

The Serverless Application Model Command Line Interface (SAM CLI) is an extension of the 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.

To use the SAM CLI, you need the following tools.

* AWS CLI - [Install the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) and [configure it with your AWS credentials].
* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)
* Golang - [Golang](https://golang.org)
* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community)

To build and deploy your application for the first time, run the following in your shell:

```bash
sam build
sam deploy --guided
```

The first command will build the source of your application. The second command will package and deploy your application to AWS, with a series of prompts:

* **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.
* **AWS Region**: The AWS region you want to deploy your app to.
* **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.
* **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.
* **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.

## Use the SAM CLI to build and test locally

Build your application with the `sam build` command.

```bash
{{ cookiecutter.project_name }}$ sam build
```

The SAM CLI installs dependencies defined in `go.mod`, creates a deployment package, and saves it in the `.aws-sam/build` folder.

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.

Run functions locally and invoke them with the `sam local invoke` command.

```bash
{{ cookiecutter.project_name }}$ sam local invoke {{cookiecutter.function_name}} --event events/event.json
```

The SAM CLI reads the application template to determine the EventBridge rule pattern and the functions that they invoke as a target. The `Events` property on each function's definition includes the source and detail-type of the types of events that will invoke the function.

```yaml
Events:
{{ cookiecutter.function_name }}:
Type: EventBridgeRule # More info about EventBridge Event Source: https://github.com/aws/serverless-application-model/blob/master/versions/2016-10-31.md#eventbridgerule
Properties:
Pattern:
source:
- {{ cookiecutter.AWS_Schema_source }}
detail-type:
- {{ cookiecutter.AWS_Schema_detail_type }}
```
## Add a resource to your application
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 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.
## Fetch, tail, and filter Lambda function logs
To simplify troubleshooting, 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.

`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM.

```bash
{{ cookiecutter.project_name }}$ sam logs -n {{cookiecutter.function_name}} --stack-name {{ cookiecutter.project_name }} --tail
```

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).

## Unit tests

We use `testing` package that is built-in in Golang and you can simply run the following command to run the tests:

```bash
go test -v ./{{cookiecutter.function_name}}/
```

## Cleanup

To delete the sample application that you created, use the SAM CLI. Assuming you used your project name for the stack name, you can run the following:

```bash
sam delete --stack-name {{ cookiecutter.project_name }}
```

## Resources

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 SAM CLI, and serverless application concepts.

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/)





Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"id":"7bf73129-1428-4cd3-a780-95db273d1602",
"detail-type":"{{ cookiecutter.AWS_Schema_detail_type }}",
"source":"{{ cookiecutter.AWS_Schema_source }}",
"account":"123456789012",
"time":"2015-11-11T21:29:54Z",
"region":"us-east-1",
"resources":[
"arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1111"
],
"detail":{
"ADD-YOUR-FIELDS-HERE":""
}
}
12 changes: 12 additions & 0 deletions go1.x/event-bridge-schema/{{cookiecutter.project_name}}/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
require github.com/aws/aws-lambda-go v1.36.1

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.7.2
gopkg.in/yaml.v3 v3.0.1 // indirect
)

module {{ cookiecutter.project_name }}

go 1.17
14 changes: 14 additions & 0 deletions go1.x/event-bridge-schema/{{cookiecutter.project_name}}/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
github.com/aws/aws-lambda-go v1.36.1 h1:CJxGkL9uKszIASRDxzcOcLX6juzTLoTKtCIgUGcTjTU=
github.com/aws/aws-lambda-go v1.36.1/go.mod h1:jwFe2KmMsHmffA1X2R09hH6lFzJQxzI8qK17ewzbQMM=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.2 h1:4jaiDzPyXQvSd7D0EjG45355tLlV3VOECpq10pLC+8s=
github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
{{ cookiecutter.project_name }}
Sample SAM Template for {{ cookiecutter.project_name }}
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 20

Resources:
{{cookiecutter.function_name}}:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: {{cookiecutter.function_name}}
Handler: hello-world
Runtime: {{ cookiecutter.runtime }}
{%- if cookiecutter.architectures.value != [] %}
Architectures:
{%- for arch in cookiecutter.architectures.value %}
- {{arch}}
{%- endfor %}
{%- endif %}
Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object
Variables:
PARAM1: VALUE
Events:
HelloWorld:
Type: EventBridgeRule # More info about EventBridge Event Source: https://github.com/aws/serverless-application-model/blob/master/versions/2016-10-31.md#eventbridgerule
Properties:
Pattern:
source:
- {{ cookiecutter.AWS_Schema_source }}
detail-type:
- {{ cookiecutter.AWS_Schema_detail_type }}

Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
{{cookiecutter.function_name}}:
Description: "Hello World Lambda Function ARN"
Value: !GetAtt {{cookiecutter.function_name}}.Arn
{{cookiecutter.function_name}}IamRole:
Description: "Implicit IAM Role created for Hello World function"
Value: !GetAtt {{cookiecutter.function_name}}.Arn
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package main

import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/lambda"
"{{ cookiecutter.codegen_path }}"
)

/*
Description: This lambda handler reads an {{ cookiecutter.AWS_Schema_detail_type }} from the inputted AWSEvent, then
updates the Detail Type (description of the type of AWS event).
Parameters:
- context: Object that provides information about the Lambda invocation, function, and execution environment.
- awsEvent: AWS EventBridge object that provides information such as the source, region, account the
event is associated with.
Output: Stream ([]byte) of the updated AWSEvent after function logic completed.
*/
func handler(context context.Context, event {{ cookiecutter.codegen_package_name }}.AWSEvent) ([]byte , error) {
// Retrieve {{ cookiecutter.AWS_Schema_name }} detail from event
detail := event.Detail
fmt.Println("Reading {{ cookiecutter.AWS_Schema_name }}: ", detail)

// Developers write your event-driven business logic code here!
// Make updates to the event payload
fmt.Println("{{ cookiecutter.function_name }} updating event of " + event.DetailType)
event.SetDetailType("{{ cookiecutter.function_name }} updated event of " + event.DetailType)

// Return event as stream for further processing
return {{ cookiecutter.codegen_package_name }}.Marshal(event)

}

func main() {
lambda.Start(handler)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package main

import (
"fmt"
"github.com/stretchr/testify/assert"
"io"
"os"
"testing"
"{{ cookiecutter.codegen_path }}"
)

var (
PathToEventJsonFile = "../events/event.json"
)

func TestHandler(t *testing.T) {
jsonFile, err := os.Open(PathToEventJsonFile)
if err != nil {
t.Fatal("Unable to open event.json")
}

fmt.Println("Successfully Opened event.json")

defer jsonFile.Close()

jsonStream, _ := io.ReadAll(jsonFile)

event, _ := {{ cookiecutter.codegen_package_name }}.UnmarshalEvent(jsonStream)

t.Run("Successful Request", func(t *testing.T) {
responseStream, err := handler(nil, event)
if err != nil {
t.Fatal("Everything should be ok")
}

responseEvent, _ := {{ cookiecutter.codegen_package_name }}.UnmarshalEvent(responseStream)

assert.NotEmpty(t, responseEvent)
assert.Equal(t, responseEvent.DetailType, "{{cookiecutter.function_name}} updated event of {{ cookiecutter.AWS_Schema_detail_type }}")
})
}
Loading

0 comments on commit 54427ad

Please sign in to comment.