Documentation ¶
Overview ¶
Package sparta transforms a set of golang functions into an Amazon Lambda deployable unit.
The deployable archive includes
- NodeJS proxy logic
- A golang binary
- Dynamically generated CloudFormation template that supports create/update & delete operations.
- If specified, CloudFormation custom resources to automatically configure S3/SNS push registration
- If specified, API Gateway provisioning logic via custom resources to make the golang functions publicly accessible.
See the Main() docs for more information and examples
Index ¶
- Constants
- Variables
- func CloudFormationResourceName(prefix string, parts ...string) string
- func Delete(serviceName string, logger *logrus.Logger) error
- func Describe(serviceName string, serviceDescription string, lambdaAWSInfos []*LambdaAWSInfo, ...) error
- func Execute(lambdaAWSInfos []*LambdaAWSInfo, port int, parentProcessPID int, ...) error
- func Explore(lambdaAWSInfos []*LambdaAWSInfo, port int, logger *logrus.Logger) error
- func Main(serviceName string, serviceDescription string, lambdaAWSInfos []*LambdaAWSInfo, ...) error
- func MainEx(serviceName string, serviceDescription string, lambdaAWSInfos []*LambdaAWSInfo, ...) error
- func NewLogger(level string) (*logrus.Logger, error)
- func ParseOptions(handler CommandLineOptionsHook) error
- func Provision(noop bool, serviceName string, serviceDescription string, ...) error
- type API
- type APIGatewayContext
- type APIGatewayIdentity
- type APIGatewayLambdaJSONEvent
- type ArbitraryJSONObject
- type ArchiveHook
- type BasePermission
- type CloudWatchEventsPermission
- type CloudWatchEventsRule
- type CloudWatchEventsRuleTarget
- type CloudWatchLogsPermission
- type CloudWatchLogsSubscriptionFilter
- type CommandLineOptionsHook
- type CustomResourceFunction
- type DiscoveryInfo
- type DiscoveryResource
- type EventSourceMapping
- type IAMRoleDefinition
- type IAMRolePrivilege
- type Integration
- type IntegrationResponse
- type LambdaAWSInfo
- type LambdaContext
- type LambdaFunction
- type LambdaFunctionOptions
- type LambdaHTTPHandler
- type LambdaPermission
- type LambdaPermissionExporter
- type MessageBodyStorage
- type MessageBodyStorageOptions
- type Method
- type Model
- type ReceiptRule
- type Resource
- type Response
- type RollbackHook
- type S3Permission
- type S3Site
- type SESPermission
- type SNSPermission
- type Stage
- type TemplateDecorator
- type WorkflowHook
- type WorkflowHooks
Examples ¶
- CloudWatchEventsPermission
- CloudWatchLogsPermission
- LambdaAWSInfo.RequireCustomResource
- Main (ApiGateway)
- Main (ApiGatewayHTTPSEvent)
- Main (Basic)
- Main (S3Site)
- NewLambda (IAMRoleDefinition)
- NewLambda (PreexistingIAMRoleName)
- ParseOptions
- S3Permission
- SESPermission (HeadersOnly)
- SESPermission (MessageBody)
- SNSPermission
- WorkflowHooks
Constants ¶
const ( // TagLogicalResourceID is the current logical resource name TagLogicalResourceID = "aws:cloudformation:logical-id" // TagResourceType is the type of the referred resource type TagResourceType = "sparta:cloudformation:restype" // TagStackRegion is the current stack's logical id TagStackRegion = "sparta:cloudformation:region" // TagStackID is the current stack's ID TagStackID = "aws:cloudformation:stack-id" // TagStackName is the current stack name TagStackName = "aws:cloudformation:stack-name" )
See http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/pseudo-parameter-reference.html
const ( // OutputSpartaHomeKey is the keyname used in the CloudFormation Output // that stores the Sparta home URL. // @enum OutputKey OutputSpartaHomeKey = "SpartaHome" // OutputSpartaVersionKey is the keyname used in the CloudFormation Output // that stores the Sparta version used to provision/update the service. // @enum OutputKey OutputSpartaVersionKey = "SpartaVersion" // OutputSpartaBuildIDKey is the keyname used in the CloudFormation Output // that stores the user-supplied or automatically generated BuildID // for this run OutputSpartaBuildIDKey = "SpartaBuildID" )
const ( // SpartaVersion defines the current Sparta release SpartaVersion = "0.8.0" // NodeJSVersion is the Node JS runtime used for the shim layer NodeJSVersion = "nodejs4.3" )
const ( // @enum AWSPrincipal APIGatewayPrincipal = "apigateway.amazonaws.com" // @enum AWSPrincipal CloudWatchEventsPrincipal = "events.amazonaws.com" // @enum AWSPrincipal SESPrincipal = "ses.amazonaws.com" // @enum AWSPrincipal SNSPrincipal = "sns.amazonaws.com" // @enum AWSPrincipal EC2Principal = "ec2.amazonaws.com" // @enum AWSPrincipal LambdaPrincipal = "lambda.amazonaws.com" )
AWS Principal ARNs from http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html See also http://docs.aws.amazon.com/general/latest/gr/rande.html for region specific principal names
const ( // OutputAPIGatewayURL is the keyname used in the CloudFormation Output // that stores the APIGateway provisioned URL // @enum OutputKey OutputAPIGatewayURL = "APIGatewayURL" )
const ( // OutputS3SiteURL is the keyname used in the CloudFormation Output // that stores the S3 backed static site provisioned with this Sparta application // @enum OutputKey OutputS3SiteURL = "S3SiteURL" )
Variables ¶
var AssumePolicyDocument = ArbitraryJSONObject{ "Version": "2012-10-17", "Statement": []ArbitraryJSONObject{ { "Effect": "Allow", "Principal": ArbitraryJSONObject{ "Service": []string{LambdaPrincipal}, }, "Action": []string{"sts:AssumeRole"}, }, { "Effect": "Allow", "Principal": ArbitraryJSONObject{ "Service": []string{EC2Principal}, }, "Action": []string{"sts:AssumeRole"}, }, { "Effect": "Allow", "Principal": ArbitraryJSONObject{ "Service": []string{APIGatewayPrincipal}, }, "Action": []string{"sts:AssumeRole"}, }, }, }
AssumePolicyDocument defines common a IAM::Role PolicyDocument used as part of IAM::Role resource definitions
var CommandLineOptions = struct { Root *cobra.Command Version *cobra.Command Provision *cobra.Command Delete *cobra.Command Execute *cobra.Command Describe *cobra.Command Explore *cobra.Command }{}
CommandLineOptions defines the commands available via the Sparta command line interface. Embedding applications can extend existing commands and add their own to the `Root` command. See https://github.com/spf13/cobra for more information.
var CommonIAMStatements = struct { Core []spartaIAM.PolicyStatement VPC []spartaIAM.PolicyStatement DynamoDB []spartaIAM.PolicyStatement Kinesis []spartaIAM.PolicyStatement }{ Core: []spartaIAM.PolicyStatement{ { Action: []string{"logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"}, Effect: "Allow", Resource: gocf.Join("", gocf.String("arn:aws:logs:"), gocf.Ref("AWS::Region"), gocf.String(":"), gocf.Ref("AWS::AccountId"), gocf.String("*")), }, { Action: []string{"cloudwatch:PutMetricData"}, Effect: "Allow", Resource: wildcardArn, }, { Effect: "Allow", Action: []string{"cloudformation:DescribeStacks", "cloudformation:DescribeStackResource"}, Resource: gocf.Join("", cloudFormationThisStackArn...), }, }, VPC: []spartaIAM.PolicyStatement{ { Action: []string{"ec2:CreateNetworkInterface", "ec2:DescribeNetworkInterfaces", "ec2:DeleteNetworkInterface"}, Effect: "Allow", Resource: wildcardArn, }, }, DynamoDB: []spartaIAM.PolicyStatement{ { Effect: "Allow", Action: []string{"dynamodb:DescribeStream", "dynamodb:GetRecords", "dynamodb:GetShardIterator", "dynamodb:ListStreams", }, }, }, Kinesis: []spartaIAM.PolicyStatement{ { Effect: "Allow", Action: []string{"kinesis:GetRecords", "kinesis:GetShardIterator", "kinesis:DescribeStream", "kinesis:ListStreams", }, }, }, }
CommonIAMStatements defines common IAM::Role Policy Statement values for different AWS service types. See http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces for names. http://docs.aws.amazon.com/lambda/latest/dg/monitoring-functions.html for more information.
var OptionsGlobal optionsGlobalStruct
OptionsGlobal stores the global command line options
var PushSourceConfigurationActions = struct { SNSLambdaEventSource []string S3LambdaEventSource []string SESLambdaEventSource []string CloudWatchLogsLambdaEventSource []string }{ SNSLambdaEventSource: []string{"sns:ConfirmSubscription", "sns:GetTopicAttributes", "sns:ListSubscriptionsByTopic", "sns:Subscribe", "sns:Unsubscribe"}, S3LambdaEventSource: []string{"s3:GetBucketLocation", "s3:GetBucketNotification", "s3:PutBucketNotification", "s3:GetBucketNotificationConfiguration", "s3:PutBucketNotificationConfiguration"}, SESLambdaEventSource: []string{"ses:CreateReceiptRuleSet", "ses:CreateReceiptRule", "ses:DeleteReceiptRule", "ses:DeleteReceiptRuleSet", "ses:DescribeReceiptRuleSet"}, CloudWatchLogsLambdaEventSource: []string{"logs:DescribeSubscriptionFilters", "logs:DeleteSubscriptionFilter", "logs:PutSubscriptionFilter", }, }
PushSourceConfigurationActions map stores common IAM Policy Actions for Lambda push-source configuration management. The configuration is handled by CustomResources inserted into the generated CloudFormation template.
Functions ¶
func CloudFormationResourceName ¶
CloudFormationResourceName returns a name suitable as a logical CloudFormation resource value. See http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html for more information. The `prefix` value should provide a hint as to the resource type (eg, `SNSConfigurator`, `ImageTranscoder`). Note that the returned name is not content-addressable.
func Delete ¶
Delete the provided serviceName. Failing to delete a non-existent service is not considered an error. Note that the delete does
func Describe ¶
func Describe(serviceName string, serviceDescription string, lambdaAWSInfos []*LambdaAWSInfo, api *API, s3Site *S3Site, outputWriter io.Writer, workflowHooks *WorkflowHooks, logger *logrus.Logger) error
Describe produces a graphical representation of a service's Lambda and data sources. Typically automatically called as part of a compiled golang binary via the `describe` command line option.
func Execute ¶
func Execute(lambdaAWSInfos []*LambdaAWSInfo, port int, parentProcessPID int, logger *logrus.Logger) error
Execute creates an HTTP listener to dispatch execution. Typically called via Main() via command line arguments.
func Explore ¶
func Explore(lambdaAWSInfos []*LambdaAWSInfo, port int, logger *logrus.Logger) error
Explore supports interactive command line invocation of the previously provisioned Sparta service
func Main ¶
func Main(serviceName string, serviceDescription string, lambdaAWSInfos []*LambdaAWSInfo, api *API, site *S3Site) error
Main defines the primary handler for transforming an application into a Sparta package. The serviceName is used to uniquely identify your service within a region and will be used for subsequent updates. For provisioning, ensure that you've properly configured AWS credentials for the golang SDK. See http://docs.aws.amazon.com/sdk-for-go/api/aws/defaults.html#DefaultChainCredentials-constant for more information.
Example (ApiGateway) ¶
Should be main() in your application
package main import ( "encoding/json" "fmt" "net/http" "github.com/Sirupsen/logrus" ) // NOTE: your application MUST use `package main` and define a `main()` function. The // example text is to make the documentation compatible with godoc. func echoAPIGatewayEvent(event *json.RawMessage, context *LambdaContext, w http.ResponseWriter, logger *logrus.Logger) { logger.WithFields(logrus.Fields{ "RequestID": context.AWSRequestID, "Event": string(*event), }).Debug("Request received") fmt.Fprintf(w, "Hello World!") } // Should be main() in your application func main() { // Create the MyEchoAPI API Gateway, with stagename /test. The associated // Stage reesource will cause the API to be deployed. stage := NewStage("test") apiGateway := NewAPIGateway("MyEchoAPI", stage) // Create a lambda function echoAPIGatewayLambdaFn := NewLambda(IAMRoleDefinition{}, echoAPIGatewayEvent, nil) // Associate a URL path component with the Lambda function apiGatewayResource, _ := apiGateway.NewResource("/echoHelloWorld", echoAPIGatewayLambdaFn) // Associate 1 or more HTTP methods with the Resource. apiGatewayResource.NewMethod("GET") // After the stack is deployed, the // echoAPIGatewayEvent lambda function will be available at: // https://{RestApiID}.execute-api.{AWSRegion}.amazonaws.com/test // // The dynamically generated URL will be written to STDOUT as part of stack provisioning as in: // // Outputs: [{ // Description: "API Gateway URL", // OutputKey: "URL", // OutputValue: "https://zdjfwrcao7.execute-api.us-west-2.amazonaws.com/test" // }] // eg: // curl -vs https://zdjfwrcao7.execute-api.us-west-2.amazonaws.com/test/echoHelloWorld // Start Main("HelloWorldLambdaService", "Description for Hello World Lambda", []*LambdaAWSInfo{echoAPIGatewayLambdaFn}, apiGateway, nil) }
Output:
Example (ApiGatewayHTTPSEvent) ¶
Should be main() in your application
package main import ( "encoding/json" "fmt" "net/http" "github.com/Sirupsen/logrus" ) // NOTE: your application MUST use `package main` and define a `main()` function. The // example text is to make the documentation compatible with godoc. func echoAPIGatewayHTTPEvent(event *json.RawMessage, context *LambdaContext, w http.ResponseWriter, logger *logrus.Logger) { var lambdaEvent APIGatewayLambdaJSONEvent err := json.Unmarshal([]byte(*event), &lambdaEvent) if err != nil { logger.Error("Failed to unmarshal event data: ", err.Error()) http.Error(w, err.Error(), http.StatusInternalServerError) return } responseBody, err := json.Marshal(lambdaEvent) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } else { fmt.Fprint(w, string(responseBody)) } } // Should be main() in your application func main() { // Create the MyEchoAPI API Gateway, with stagename /test. The associated // Stage reesource will cause the API to be deployed. stage := NewStage("v1") apiGateway := NewAPIGateway("MyEchoHTTPAPI", stage) // Create a lambda function echoAPIGatewayLambdaFn := NewLambda(IAMRoleDefinition{}, echoAPIGatewayEvent, nil) // Associate a URL path component with the Lambda function apiGatewayResource, _ := apiGateway.NewResource("/echoHelloWorld", echoAPIGatewayLambdaFn) // Associate 1 or more HTTP methods with the Resource. method, err := apiGatewayResource.NewMethod("GET") if err != nil { panic("Failed to create NewMethod") } // Whitelist query parameters that should be passed to lambda function method.Parameters["method.request.querystring.myKey"] = true method.Parameters["method.request.querystring.myOtherKey"] = true // Start Main("HelloWorldLambdaHTTPSService", "Description for Hello World HTTPS Lambda", []*LambdaAWSInfo{echoAPIGatewayLambdaFn}, apiGateway, nil) }
Output:
Example (Basic) ¶
package main import ( "encoding/json" "fmt" "net/http" "github.com/Sirupsen/logrus" ) // NOTE: your application MUST use `package main` and define a `main()` function. The // example text is to make the documentation compatible with godoc. // Should be main() in your application func mainHelloWorld(event *json.RawMessage, context *LambdaContext, w http.ResponseWriter, logger *logrus.Logger) { fmt.Fprintf(w, "Hello World!") } func main() { var lambdaFunctions []*LambdaAWSInfo helloWorldLambda := NewLambda("PreexistingAWSLambdaRoleName", mainHelloWorld, nil) lambdaFunctions = append(lambdaFunctions, helloWorldLambda) Main("HelloWorldLambdaService", "Description for Hello World Lambda", lambdaFunctions, nil, nil) }
Output:
Example (S3Site) ¶
Should be main() in your application
package main import ( "encoding/json" "fmt" "net/http" "github.com/Sirupsen/logrus" ) // NOTE: your application MUST use `package main` and define a `main()` function. The // example text is to make the documentation compatible with godoc. func echoS3SiteAPIGatewayEvent(event *json.RawMessage, context *LambdaContext, w http.ResponseWriter, logger *logrus.Logger) { logger.Info("Hello World: ", string(*event)) fmt.Fprint(w, string(*event)) } // Should be main() in your application func main() { // Create an API Gateway apiStage := NewStage("v1") apiGateway := NewAPIGateway("SpartaS3Site", apiStage) apiGateway.CORSEnabled = true // Create a lambda function echoS3SiteAPIGatewayEventLambdaFn := NewLambda(IAMRoleDefinition{}, echoAPIGatewayEvent, nil) apiGatewayResource, _ := apiGateway.NewResource("/hello", echoS3SiteAPIGatewayEventLambdaFn) _, err := apiGatewayResource.NewMethod("GET") if nil != err { panic("Failed to create GET resource") } // Create an S3 site from the contents in ./site s3Site, _ := NewS3Site("./site") // Provision everything Main("HelloWorldS3SiteService", "Description for S3Site", []*LambdaAWSInfo{echoS3SiteAPIGatewayEventLambdaFn}, apiGateway, s3Site) }
Output:
func MainEx ¶
func MainEx(serviceName string, serviceDescription string, lambdaAWSInfos []*LambdaAWSInfo, api *API, site *S3Site, workflowHooks *WorkflowHooks) error
MainEx provides an "extended" Main that supports customizing the standard Sparta workflow via the `workflowHooks` parameter.
func NewLogger ¶
NewLogger returns a new logrus.Logger instance. It is the caller's responsibility to set the formatter if needed.
func ParseOptions ¶
func ParseOptions(handler CommandLineOptionsHook) error
ParseOptions the command line options
Example ¶
package main import ( "fmt" "github.com/asaskevich/govalidator" "github.com/spf13/cobra" "os" ) // NOTE: your application MUST use `package main` and define a `main()` function. The // example text is to make the documentation compatible with godoc. // Should be main() in your application // Additional command line options used for both the provision // and CLI commands type optionsStruct struct { Username string `valid:"required,match(\\w+)"` Password string `valid:"required,match(\\w+)"` SSHKeyName string `valid:"-"` } var options optionsStruct // Common function to register shared command line flags // across multiple Sparta commands func registerSpartaCommandLineFlags(command *cobra.Command) { command.Flags().StringVarP(&options.Username, "username", "u", "", "HTTP Basic Auth username") command.Flags().StringVarP(&options.Password, "password", "p", "", "HTTP Basic Auth password") } func main() { ////////////////////////////////////////////////////////////////////////////// // Add the custom command to run the sync loop syncCommand := &cobra.Command{ Use: "sync", Short: "Periodically perform a task", RunE: func(cmd *cobra.Command, args []string) error { fmt.Printf("Sync command!\n") return nil }, } // Include the basic auth flags for the sync command registerSpartaCommandLineFlags(syncCommand) CommandLineOptions.Root.AddCommand(syncCommand) ////////////////////////////////////////////////////////////////////////////// // Register custom flags for pre-existing Sparta commands registerSpartaCommandLineFlags(CommandLineOptions.Provision) CommandLineOptions.Provision.Flags().StringVarP(&options.SSHKeyName, "key", "k", "", "SSH Key Name to use for EC2 instances") ////////////////////////////////////////////////////////////////////////////// // Define a validation hook s.t. we can validate the CLI user input validationHook := func(command *cobra.Command) error { if command.Name() == "provision" && len(options.SSHKeyName) <= 0 { return fmt.Errorf("SSHKeyName option is required") } fmt.Printf("Command: %s\n", command.Name()) switch command.Name() { case "provision", "sync": _, validationErr := govalidator.ValidateStruct(options) return validationErr default: return nil } } // If the validation hooks failed, exit the application parseErr := ParseOptions(validationHook) if nil != parseErr { os.Exit(3) } ////////////////////////////////////////////////////////////////////////////// // // Standard Sparta application // ... }
Output:
func Provision ¶
func Provision(noop bool, serviceName string, serviceDescription string, lambdaAWSInfos []*LambdaAWSInfo, api *API, site *S3Site, s3Bucket string, buildID string, templateWriter io.Writer, workflowHooks *WorkflowHooks, logger *logrus.Logger) error
Provision compiles, packages, and provisions (either via create or update) a Sparta application. The serviceName is the service's logical identify and is used to determine create vs update operations. The compilation options/flags are:
TAGS: -tags lambdabinary ENVIRONMENT: GOOS=linux GOARCH=amd64
The compiled binary is packaged with a NodeJS proxy shim to manage AWS Lambda setup & invocation per http://docs.aws.amazon.com/lambda/latest/dg/authoring-function-in-nodejs.html
The two files are ZIP'd, posted to S3 and used as an input to a dynamically generated CloudFormation template (http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) which creates or updates the service state.
More information on golang 1.5's support for vendor'd resources is documented at
https://docs.google.com/document/d/1Bz5-UB7g2uPBdOx-rw5t9MxJwkfpx90cqG9AFL0JAYo/edit https://medium.com/@freeformz/go-1-5-s-vendor-experiment-fd3e830f52c3#.voiicue1j
type Configuration struct { Val string Proxy struct { Address string Port string } }
Types ¶
type API ¶
type API struct { // Existing API to CloneFrom CloneFrom string // API Description Description string // Should CORS be enabled for this API? CORSEnabled bool // contains filtered or unexported fields }
API represents the AWS API Gateway data associated with a given Sparta app. Proxies the AWS SDK's CreateRestApiInput data. See http://docs.aws.amazon.com/sdk-for-go/api/service/apigateway.html#type-CreateRestApiInput
func NewAPIGateway ¶
NewAPIGateway returns a new API Gateway structure. If stage is defined, the API Gateway will also be deployed as part of stack creation.
func (*API) NewResource ¶
func (api *API) NewResource(pathPart string, parentLambda *LambdaAWSInfo) (*Resource, error)
NewResource associates a URL path value with the LambdaAWSInfo golang lambda. To make the Resource available, associate one or more Methods via NewMethod().
type APIGatewayContext ¶
type APIGatewayContext struct { // API ID APIID string `json:"apiId"` // HTTPMethod Method string `json:"method"` // Request ID RequestID string `json:"requestId"` // Resource ID ResourceID string `json:"resourceId"` // Resource Path ResourcePath string `json:"resourcePath"` // Stage Stage string `json:"stage"` // User identity Identity APIGatewayIdentity `json:"identity"` }
APIGatewayContext represents the context available to an AWS Lambda function that is invoked by an API Gateway integration.
type APIGatewayIdentity ¶
type APIGatewayIdentity struct { // Account ID AccountID string `json:"accountId"` // API Key APIKey string `json:"apiKey"` // Caller Caller string `json:"caller"` // Cognito Authentication Provider CognitoAuthenticationProvider string `json:"cognitoAuthenticationProvider"` // Cognito Authentication Type CognitoAuthenticationType string `json:"cognitoAuthenticationType"` // CognitoIdentityId CognitoIdentityID string `json:"cognitoIdentityId"` // CognitoIdentityPoolId CognitoIdentityPoolID string `json:"cognitoIdentityPoolId"` // Source IP SourceIP string `json:"sourceIp"` // User User string `json:"user"` // User Agent UserAgent string `json:"userAgent"` // User ARN UserARN string `json:"userArn"` }
APIGatewayIdentity represents the user identity of a request made on behalf of the API Gateway
type APIGatewayLambdaJSONEvent ¶
type APIGatewayLambdaJSONEvent struct { // HTTPMethod Method string `json:"method"` // Body, if available Body json.RawMessage `json:"body"` // Whitelisted HTTP headers Headers map[string]string `json:"headers"` // Whitelisted HTTP query params QueryParams map[string]string `json:"queryParams"` // Whitelisted path parameters PathParams map[string]string `json:"pathParams"` // Context information - http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#context-variable-reference Context APIGatewayContext `json:"context"` }
APIGatewayLambdaJSONEvent provides a pass through mapping of all whitelisted Parameters. The transformation is defined by the resources/gateway/inputmapping_json.vtl template.
type ArbitraryJSONObject ¶
type ArbitraryJSONObject map[string]interface{}
ArbitraryJSONObject represents an untyped key-value object. CloudFormation resource representations are aggregated as []ArbitraryJSONObject before being marsharled to JSON for API operations.
type ArchiveHook ¶
type ArchiveHook func(context map[string]interface{}, serviceName string, zipWriter *zip.Writer, awsSession *session.Session, noop bool, logger *logrus.Logger) error
ArchiveHook provides callers an opportunity to insert additional files into the ZIP archive deployed to S3
type BasePermission ¶
type BasePermission struct { // The AWS account ID (without hyphens) of the source owner SourceAccount string `json:"SourceAccount,omitempty"` // The ARN of a resource that is invoking your function. SourceArn interface{} `json:"SourceArn,omitempty"` }
BasePermission (http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-permission.html) type for common AWS Lambda permission data.
type CloudWatchEventsPermission ¶
type CloudWatchEventsPermission struct { BasePermission // Map of rule names to events that trigger the lambda function Rules map[string]CloudWatchEventsRule }
CloudWatchEventsPermission struct implies that the CloudWatchEvent sources should be configured as part of provisioning. The BasePermission.SourceArn isn't considered for this configuration. Each CloudWatchEventsRule struct in the Rules map is used to register for push based event notifications via `putRule` and `deleteRule`. See http://docs.aws.amazon.com/lambda/latest/dg/intro-core-components.html#intro-core-components-event-sources for more information.
Example ¶
package main import ( "encoding/json" "net/http" "github.com/Sirupsen/logrus" ) func cloudWatchEventProcessor(event *json.RawMessage, context *LambdaContext, w http.ResponseWriter, logger *logrus.Logger) { logger.WithFields(logrus.Fields{ "RequestID": context.AWSRequestID, }).Info("Request received") logger.Info("CloudWatch Event data: ", string(*event)) } func main() { cloudWatchEventsLambda := NewLambda(IAMRoleDefinition{}, cloudWatchEventProcessor, nil) cloudWatchEventsPermission := CloudWatchEventsPermission{} cloudWatchEventsPermission.Rules = make(map[string]CloudWatchEventsRule, 0) cloudWatchEventsPermission.Rules["Rate5Mins"] = CloudWatchEventsRule{ ScheduleExpression: "rate(5 minutes)", } cloudWatchEventsPermission.Rules["EC2Activity"] = CloudWatchEventsRule{ EventPattern: map[string]interface{}{ "source": []string{"aws.ec2"}, "detail-type": []string{"EC2 Instance State-change Notification"}, }, } cloudWatchEventsLambda.Permissions = append(cloudWatchEventsLambda.Permissions, cloudWatchEventsPermission) var lambdaFunctions []*LambdaAWSInfo lambdaFunctions = append(lambdaFunctions, cloudWatchEventsLambda) Main("CloudWatchLogs", "Registers for CloudWatch Logs", lambdaFunctions, nil, nil) }
Output:
type CloudWatchEventsRule ¶
type CloudWatchEventsRule struct { Description string // ArbitraryJSONObject filter for events as documented at // http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/CloudWatchEventsandEventPatterns.html // Rules matches should use the JSON representation (NOT the string form). Sparta will serialize // the map[string]interface{} to a string form during CloudFormation Template // marshalling. EventPattern map[string]interface{} `json:"EventPattern,omitempty"` // Schedule pattern per http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/ScheduledEvents.html ScheduleExpression string RuleTarget *CloudWatchEventsRuleTarget `json:"RuleTarget,omitempty"` }
CloudWatchEventsRule defines parameters for invoking a lambda function in response to specific CloudWatchEvents or cron triggers
func (CloudWatchEventsRule) MarshalJSON ¶
func (rule CloudWatchEventsRule) MarshalJSON() ([]byte, error)
MarshalJSON customizes the JSON representation used when serializing to the CloudFormation template representation.
type CloudWatchEventsRuleTarget ¶
CloudWatchEventsRuleTarget specifies additional input and JSON selection paths to apply prior to forwarding the event to a lambda function
type CloudWatchLogsPermission ¶
type CloudWatchLogsPermission struct { BasePermission // Map of filter names to the CloudWatchLogsSubscriptionFilter settings Filters map[string]CloudWatchLogsSubscriptionFilter }
CloudWatchLogsPermission struct implies that the corresponding CloudWatchLogsSubscriptionFilter definitions should be configured during stack provisioning. The BasePermission.SourceArn isn't considered for this configuration operation. Configuration of the remote push source is done via `putSubscriptionFilter` and `deleteSubscriptionFilter`. See http://docs.aws.amazon.com/lambda/latest/dg/intro-core-components.html#intro-core-components-event-sources for more information.
Example ¶
package main import ( "encoding/json" "net/http" "github.com/Sirupsen/logrus" ) func cloudWatchLogsProcessor(event *json.RawMessage, context *LambdaContext, w http.ResponseWriter, logger *logrus.Logger) { logger.WithFields(logrus.Fields{ "RequestID": context.AWSRequestID, }).Info("CloudWatch log event") logger.Info("CloudWatch Log event data: ", string(*event)) } func main() { var lambdaFunctions []*LambdaAWSInfo cloudWatchLogsLambda := NewLambda(IAMRoleDefinition{}, cloudWatchLogsProcessor, nil) cloudWatchLogsPermission := CloudWatchLogsPermission{} cloudWatchLogsPermission.Filters = make(map[string]CloudWatchLogsSubscriptionFilter, 1) cloudWatchLogsPermission.Filters["MyFilter"] = CloudWatchLogsSubscriptionFilter{ LogGroupName: "/aws/lambda/*", } cloudWatchLogsLambda.Permissions = append(cloudWatchLogsLambda.Permissions, cloudWatchLogsPermission) lambdaFunctions = append(lambdaFunctions, cloudWatchLogsLambda) Main("CloudWatchLogs", "Registers for CloudWatch Logs", lambdaFunctions, nil, nil) }
Output:
type CloudWatchLogsSubscriptionFilter ¶
CloudWatchLogsSubscriptionFilter represents the CloudWatch Log filter information
type CommandLineOptionsHook ¶
CommandLineOptionsHook allows embedding applications the ability to validate caller-defined command line arguments. Return an error if the command line fails.
type CustomResourceFunction ¶
type CustomResourceFunction func(requestType string, stackID string, properties map[string]interface{}, logger *logrus.Logger) (map[string]interface{}, error)
CustomResourceFunction represents a user-defined function that is used as a CloudFormation lambda backed resource target
type DiscoveryInfo ¶
type DiscoveryInfo struct { // Current logical resource ID ResourceID string // Current AWS region Region string // Current Stack ID StackID string // StackName (eg, Sparta service name) StackName string // Map of resources this Go function has explicit `DependsOn` relationship Resources map[string]DiscoveryResource }
DiscoveryInfo encapsulates information returned by `sparta.Discovery()` to enable a runtime function to discover information about its AWS environment or resources that the function created explicit `DependsOn` relationships
func Discover ¶
func Discover() (*DiscoveryInfo, error)
Discover returns metadata information for resources upon which the current golang lambda function depends.
func (*DiscoveryInfo) UnmarshalJSON ¶
func (discoveryInfo *DiscoveryInfo) UnmarshalJSON(data []byte) error
UnmarshalJSON is responsible for transforming the raw discovery data into
type DiscoveryResource ¶
type DiscoveryResource struct { ResourceID string Properties map[string]string Tags map[string]string }
DiscoveryResource stores information about a CloudFormation resource that the calling Go function `DependsOn`.
type EventSourceMapping ¶
type EventSourceMapping struct { StartingPosition string EventSourceArn string Disabled bool BatchSize int64 }
EventSourceMapping specifies data necessary for pull-based configuration. The fields directly correspond to the golang AWS SDK's CreateEventSourceMappingInput (http://docs.aws.amazon.com/sdk-for-go/api/service/lambda.html#type-CreateEventSourceMappingInput)
type IAMRoleDefinition ¶
type IAMRoleDefinition struct { // Slice of IAMRolePrivilege entries Privileges []IAMRolePrivilege // contains filtered or unexported fields }
IAMRoleDefinition stores a slice of IAMRolePrivilege values to "Allow" for the given IAM::Role. Note that the CommonIAMStatements will be automatically included and do not need to be multiply specified.
type IAMRolePrivilege ¶
type IAMRolePrivilege struct { // What actions you will allow. // Each AWS service has its own set of actions. // For example, you might allow a user to use the Amazon S3 ListBucket action, // which returns information about the items in a bucket. // Any actions that you don't explicitly allow are denied. Actions []string // Which resources you allow the action on. For example, what specific Amazon // S3 buckets will you allow the user to perform the ListBucket action on? // Users cannot access any resources that you have not explicitly granted // permissions to. Resource interface{} }
IAMRolePrivilege struct stores data necessary to create an IAM Policy Document as part of the inline IAM::Role resource definition. See http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html for more information
type Integration ¶
type Integration struct { Parameters map[string]string RequestTemplates map[string]string CacheKeyParameters []string CacheNamespace string Credentials string Responses map[int]*IntegrationResponse // contains filtered or unexported fields }
Integration proxies the AWS SDK's Integration data. See http://docs.aws.amazon.com/sdk-for-go/api/service/apigateway.html#type-Integration
type IntegrationResponse ¶
type IntegrationResponse struct { Parameters map[string]string `json:",omitempty"` SelectionPattern string `json:",omitempty"` Templates map[string]string `json:",omitempty"` }
IntegrationResponse proxies the AWS SDK's IntegrationResponse data. See http://docs.aws.amazon.com/sdk-for-go/api/service/apigateway.html#type-IntegrationResponse
type LambdaAWSInfo ¶
type LambdaAWSInfo struct { // Role name (NOT ARN) to use during AWS Lambda Execution. See // the FunctionConfiguration (http://docs.aws.amazon.com/lambda/latest/dg/API_FunctionConfiguration.html) // docs for more info. // Note that either `RoleName` or `RoleDefinition` must be supplied RoleName string // IAM Role Definition if the stack should implicitly create an IAM role for // lambda execution. Note that either `RoleName` or `RoleDefinition` must be supplied RoleDefinition *IAMRoleDefinition // Additional exeuction options Options *LambdaFunctionOptions // Permissions to enable push-based Lambda execution. See the // Permission Model docs (http://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html) // for more information. Permissions []LambdaPermissionExporter // EventSource mappings to enable for pull-based Lambda execution. See the // Event Source docs (http://docs.aws.amazon.com/lambda/latest/dg/intro-core-components.html) // for more information EventSourceMappings []*EventSourceMapping // Template decorator. If defined, the decorator will be called to insert additional // resources on behalf of this lambda function Decorator TemplateDecorator // Optional array of infrastructure resource logical names, typically // defined by a TemplateDecorator, that this lambda depends on DependsOn []string // contains filtered or unexported fields }
LambdaAWSInfo stores all data necessary to provision a golang-based AWS Lambda function.
func NewLambda ¶
func NewLambda(roleNameOrIAMRoleDefinition interface{}, fn LambdaFunction, lambdaOptions *LambdaFunctionOptions) *LambdaAWSInfo
NewLambda returns a LambdaAWSInfo value that can be provisioned via CloudFormation. The roleNameOrIAMRoleDefinition must either be a `string` or `IAMRoleDefinition` type
Example (IAMRoleDefinition) ¶
package main import ( "encoding/json" "fmt" "net/http" "github.com/Sirupsen/logrus" ) func lambdaHelloWorld2(event *json.RawMessage, context *LambdaContext, w http.ResponseWriter, logger *logrus.Logger) { fmt.Fprintf(w, "Hello World!") } func main() { roleDefinition := IAMRoleDefinition{} roleDefinition.Privileges = append(roleDefinition.Privileges, IAMRolePrivilege{ Actions: []string{"s3:GetObject", "s3:PutObject"}, Resource: "arn:aws:s3:::*", }) helloWorldLambda := NewLambda(IAMRoleDefinition{}, lambdaHelloWorld2, nil) if nil != helloWorldLambda { fmt.Printf("Failed to create new Lambda function") } }
Output:
Example (PreexistingIAMRoleName) ¶
package main import ( "encoding/json" "fmt" "net/http" "github.com/Sirupsen/logrus" ) func lambdaHelloWorld(event *json.RawMessage, context *LambdaContext, w http.ResponseWriter, logger *logrus.Logger) { fmt.Fprintf(w, "Hello World!") } func main() { helloWorldLambda := NewLambda("PreexistingAWSLambdaRoleName", lambdaHelloWorld, nil) if nil != helloWorldLambda { fmt.Printf("Failed to create new Lambda function") } }
Output:
func (*LambdaAWSInfo) RequireCustomResource ¶
func (info *LambdaAWSInfo) RequireCustomResource(roleNameOrIAMRoleDefinition interface{}, userFunc CustomResourceFunction, lambdaOptions *LambdaFunctionOptions, resourceProps map[string]interface{}) (string, error)
RequireCustomResource adds a Lambda-backed CustomResource entry to the CloudFormation template. This function will be made a dependency of the owning Lambda function. The returned string is the custom resource's CloudFormation logical resource name that can be used for `Fn:GetAtt` calls for metadata lookups
Example ¶
package main import ( "encoding/json" "fmt" "net/http" gocf "github.com/crewjam/go-cloudformation" "github.com/Sirupsen/logrus" ) // Standard AWS λ function func helloWorld(event *json.RawMessage, context *LambdaContext, w http.ResponseWriter, logger *logrus.Logger) { configuration, _ := Discover() logger.WithFields(logrus.Fields{ "Discovery": configuration, }).Info("Custom resource request") fmt.Fprint(w, "Hello World") } // User defined λ-backed CloudFormation CustomResource func userDefinedCustomResource(requestType string, stackID string, properties map[string]interface{}, logger *logrus.Logger) (map[string]interface{}, error) { var results = map[string]interface{}{ "CustomResourceResult": "Victory!", } return results, nil } func main() { lambdaFn := NewLambda(IAMRoleDefinition{}, helloWorld, nil) cfResName, _ := lambdaFn.RequireCustomResource(IAMRoleDefinition{}, userDefinedCustomResource, nil, nil) lambdaFn.Decorator = func(serviceName string, lambdaResourceName string, lambdaResource gocf.LambdaFunction, resourceMetadata map[string]interface{}, S3Bucket string, S3Key string, buildID string, cfTemplate *gocf.Template, context map[string]interface{}, logger *logrus.Logger) error { // Pass CustomResource outputs to the λ function resourceMetadata["CustomResource"] = gocf.GetAtt(cfResName, "CustomResourceResult") return nil } var lambdaFunctions []*LambdaAWSInfo lambdaFunctions = append(lambdaFunctions, lambdaFn) Main("SpartaUserCustomResource", "Uses a user-defined CloudFormation CustomResource", lambdaFunctions, nil, nil) }
Output:
func (*LambdaAWSInfo) URLPath ¶
func (info *LambdaAWSInfo) URLPath() string
URLPath returns the URL path that can be used as an argument to NewLambdaRequest or NewAPIGatewayRequest
type LambdaContext ¶
type LambdaContext struct { AWSRequestID string `json:"awsRequestId"` InvokeID string `json:"invokeid"` LogGroupName string `json:"logGroupName"` LogStreamName string `json:"logStreamName"` FunctionName string `json:"functionName"` MemoryLimitInMB string `json:"memoryLimitInMB"` FunctionVersion string `json:"functionVersion"` InvokedFunctionARN string `json:"invokedFunctionArn"` }
LambdaContext defines the AWS Lambda Context object provided by the AWS Lambda runtime. See http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html for more information on field values. Note that the golang version doesn't functions defined on the Context object.
type LambdaFunction ¶
type LambdaFunction func(*json.RawMessage, *LambdaContext, http.ResponseWriter, *logrus.Logger)
LambdaFunction is the golang function signature required to support AWS Lambda execution. Standard HTTP response codes are used to signal AWS Lambda success/failure on the proxied context() object. See http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html for more information.
200 - 299 : Success <200 || >= 300 : Failure
Content written to the ResponseWriter will be used as the response/Error value provided to AWS Lambda.
type LambdaFunctionOptions ¶
type LambdaFunctionOptions struct { // Additional function description Description string // Memory limit MemorySize int64 // Timeout (seconds) Timeout int64 // VPC Settings VpcConfig *gocf.LambdaFunctionVPCConfig }
LambdaFunctionOptions defines additional AWS Lambda execution params. See the AWS Lambda FunctionConfiguration (http://docs.aws.amazon.com/lambda/latest/dg/API_FunctionConfiguration.html) docs for more information. Note that the "Runtime" field will be automatically set to "nodejs4.3" (at least until golang is officially supported). See http://docs.aws.amazon.com/lambda/latest/dg/programming-model.html
type LambdaHTTPHandler ¶
type LambdaHTTPHandler struct {
// contains filtered or unexported fields
}
LambdaHTTPHandler is an HTTP compliant handler that implements ServeHTTP
func NewLambdaHTTPHandler ¶
func NewLambdaHTTPHandler(lambdaAWSInfos []*LambdaAWSInfo, logger *logrus.Logger) *LambdaHTTPHandler
NewLambdaHTTPHandler returns an initialized LambdaHTTPHandler instance. The returned value can be provided to https://golang.org/pkg/net/http/httptest/#NewServer to perform localhost testing.
func (*LambdaHTTPHandler) ServeHTTP ¶
func (handler *LambdaHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)
type LambdaPermission ¶
type LambdaPermission struct { BasePermission // The entity for which you are granting permission to invoke the Lambda function Principal string }
LambdaPermission type that creates a Lambda::Permission entry in the generated template, but does NOT automatically register the lambda with the BasePermission.SourceArn. Typically used to register lambdas with externally managed event producers
type LambdaPermissionExporter ¶
type LambdaPermissionExporter interface {
// contains filtered or unexported methods
}
LambdaPermissionExporter defines an interface for polymorphic collection of Permission entries that support specialization for additional resource generation.
type MessageBodyStorage ¶
type MessageBodyStorage struct {
// contains filtered or unexported fields
}
MessageBodyStorage represents either a new S3 bucket or an existing S3 bucket to which SES message bodies should be stored. NOTE: New MessageBodyStorage create S3 buckets which will be orphaned after your service is deleted.
func (*MessageBodyStorage) BucketArn ¶
func (storage *MessageBodyStorage) BucketArn() *gocf.StringExpr
BucketArn returns an Arn value that can be used as an lambdaFn.RoleDefinition.Privileges `Resource` value.
func (*MessageBodyStorage) BucketArnAllKeys ¶
func (storage *MessageBodyStorage) BucketArnAllKeys() *gocf.StringExpr
BucketArnAllKeys returns an Arn value that can be used lambdaFn.RoleDefinition.Privileges `Resource` value. It includes the trailing `/*` wildcard to support item acccess
type MessageBodyStorageOptions ¶
type MessageBodyStorageOptions struct { ObjectKeyPrefix string KmsKeyArn string TopicArn string DisableStorage bool }
MessageBodyStorageOptions define additional options for storing SES message body content. By default, all rules associated with the owning SESPermission object will store message bodies if the MessageBodyStorage field is non-nil. Message bodies are by default prefixed with `ServiceName/RuleName/`, which can be overridden by specifying a non-empty ObjectKeyPrefix value. A rule can opt-out of message body storage with the DisableStorage field. See http://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-action-s3.html for additional field documentation. The message body is saved as MIME (https://tools.ietf.org/html/rfc2045)
type Method ¶
type Method struct { APIKeyRequired bool // Request data Parameters map[string]bool Models map[string]*Model // Response map Responses map[int]*Response // Integration response map Integration Integration // contains filtered or unexported fields }
Method proxies the AWS SDK's Method data. See http://docs.aws.amazon.com/sdk-for-go/api/service/apigateway.html#type-Method
type Model ¶
type Model struct { Description string `json:",omitempty"` Name string `json:",omitempty"` Schema string `json:",omitempty"` }
Model proxies the AWS SDK's Model data. See http://docs.aws.amazon.com/sdk-for-go/api/service/apigateway.html#type-Model
TODO: Support Dynamic Model creation
type ReceiptRule ¶
type ReceiptRule struct { Name string Disabled bool Recipients []string ScanDisabled bool TLSPolicy string TopicArn string InvocationType string BodyStorageOptions MessageBodyStorageOptions }
ReceiptRule represents an SES ReceiptRule (http://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-receipt-rules.html) value. To store message bodies, provide a non-nil MessageBodyStorage value to the owning SESPermission object
type Resource ¶
Resource proxies the AWS SDK's Resource data. See http://docs.aws.amazon.com/sdk-for-go/api/service/apigateway.html#type-Resource
type Response ¶
type Response struct { Parameters map[string]bool `json:",omitempty"` Models map[string]*Model `json:",omitempty"` }
Response proxies the AWS SDK's PutMethodResponseInput data. See http://docs.aws.amazon.com/sdk-for-go/api/service/apigateway.html#type-PutMethodResponseInput
type RollbackHook ¶
type RollbackHook func(context map[string]interface{}, serviceName string, awsSession *session.Session, noop bool, logger *logrus.Logger)
RollbackHook provides callers an opportunity to handle failures associated with failing to perform the requested operation
type S3Permission ¶
type S3Permission struct { BasePermission // S3 events to register for (eg: `[]string{s3:GetObjectObjectCreated:*", "s3:ObjectRemoved:*"}`). Events []string `json:"Events,omitempty"` // S3.NotificationConfigurationFilter // to scope event forwarding. See // http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html // for more information. Filter s3.NotificationConfigurationFilter `json:"Filter,omitempty"` }
S3Permission struct implies that the S3 BasePermission.SourceArn should be updated (via PutBucketNotificationConfiguration) to automatically push events to the owning Lambda. See http://docs.aws.amazon.com/lambda/latest/dg/intro-core-components.html#intro-core-components-event-sources for more information.
Example ¶
package main import ( "encoding/json" "net/http" "github.com/Sirupsen/logrus" ) const s3Bucket = "arn:aws:sns:us-west-2:123412341234:myBucket" func s3LambdaProcessor(event *json.RawMessage, context *LambdaContext, w http.ResponseWriter, logger *logrus.Logger) { logger.WithFields(logrus.Fields{ "RequestID": context.AWSRequestID, }).Info("S3Event") logger.Info("Event data: ", string(*event)) } func main() { var lambdaFunctions []*LambdaAWSInfo // Define the IAM role roleDefinition := IAMRoleDefinition{} roleDefinition.Privileges = append(roleDefinition.Privileges, IAMRolePrivilege{ Actions: []string{"s3:GetObject", "s3:PutObject"}, Resource: s3Bucket, }) // Create the Lambda s3Lambda := NewLambda(IAMRoleDefinition{}, s3LambdaProcessor, nil) // Add a Permission s.t. the Lambda function automatically registers for S3 events s3Lambda.Permissions = append(s3Lambda.Permissions, S3Permission{ BasePermission: BasePermission{ SourceArn: s3Bucket, }, Events: []string{"s3:ObjectCreated:*", "s3:ObjectRemoved:*"}, }) lambdaFunctions = append(lambdaFunctions, s3Lambda) Main("S3LambdaApp", "Registers for S3 events", lambdaFunctions, nil, nil) }
Output:
type S3Site ¶
type S3Site struct { // If nil, defaults to ErrorDocument: error.html and IndexDocument: index.html WebsiteConfiguration *s3.WebsiteConfiguration // contains filtered or unexported fields }
S3Site provisions a new, publicly available S3Bucket populated by the contents of the resources directory. http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-s3.html#scenario-s3-bucket-website-customdomain
type SESPermission ¶
type SESPermission struct { BasePermission InvocationType string /* RequestResponse, Event */ ReceiptRules []ReceiptRule MessageBodyStorage *MessageBodyStorage }
SESPermission struct implies that the SES verified domain should be updated (via createReceiptRule) to automatically request or push events to the parent lambda See http://docs.aws.amazon.com/lambda/latest/dg/intro-core-components.html#intro-core-components-event-sources for more information. See http://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-concepts.html for setting up email receiving.
Example (HeadersOnly) ¶
var lambdaFunctions []*LambdaAWSInfo // Define the IAM role roleDefinition := IAMRoleDefinition{} sesLambda := NewLambda(roleDefinition, sesLambdaProcessor, nil) // Add a Permission s.t. the Lambda function is automatically invoked // in response to inbound email lambdaSESPermission := SESPermission{ BasePermission: BasePermission{ SourceArn: "*", }, InvocationType: "Event", } // Add some custom ReceiptRules. Rules will be inserted (evaluated) in their // array rank order. lambdaSESPermission.ReceiptRules = make([]ReceiptRule, 0) lambdaSESPermission.ReceiptRules = append(lambdaSESPermission.ReceiptRules, ReceiptRule{ Name: "Special", Recipients: []string{"somebody@mydomain.io"}, TLSPolicy: "Optional", }) lambdaSESPermission.ReceiptRules = append(lambdaSESPermission.ReceiptRules, ReceiptRule{ Name: "Default", Recipients: []string{}, TLSPolicy: "Optional", }) sesLambda.Permissions = append(sesLambda.Permissions, lambdaSESPermission) lambdaFunctions = append(lambdaFunctions, sesLambda) Main("SESLambdaApp", "Registers for SES events", lambdaFunctions, nil, nil)
Output:
Example (MessageBody) ¶
var lambdaFunctions []*LambdaAWSInfo // Define the IAM role roleDefinition := IAMRoleDefinition{} sesLambda := NewLambda(roleDefinition, sesLambdaProcessor, nil) // Add a Permission s.t. the Lambda function is automatically invoked // in response to inbound email lambdaSESPermission := SESPermission{ BasePermission: BasePermission{ SourceArn: "*", }, InvocationType: "Event", } // Store the message body in a newly provisioned S3 bucket bodyStorage, _ := lambdaSESPermission.NewMessageBodyStorageResource("MessageBody") lambdaSESPermission.MessageBodyStorage = bodyStorage // Add some custom ReceiptRules. lambdaSESPermission.ReceiptRules = append(lambdaSESPermission.ReceiptRules, ReceiptRule{ Name: "Default", Recipients: []string{}, TLSPolicy: "Optional", }) sesLambda.Permissions = append(sesLambda.Permissions, lambdaSESPermission) lambdaFunctions = append(lambdaFunctions, sesLambda) Main("SESLambdaApp", "Registers for SES events and saves the MessageBody", lambdaFunctions, nil, nil)
Output:
func (*SESPermission) NewMessageBodyStorageReference ¶
func (perm *SESPermission) NewMessageBodyStorageReference(prexistingBucketName string) (*MessageBodyStorage, error)
NewMessageBodyStorageReference uses a pre-existing S3 bucket for MessageBody storage. Sparta assumes that prexistingBucketName exists and will add an S3::BucketPolicy to enable SES PutObject access.
func (*SESPermission) NewMessageBodyStorageResource ¶
func (perm *SESPermission) NewMessageBodyStorageResource(bucketLogicalName string) (*MessageBodyStorage, error)
NewMessageBodyStorageResource provisions a new S3 bucket to store message body content.
type SNSPermission ¶
type SNSPermission struct {
BasePermission
}
SNSPermission struct implies that the BasePermisison.SourceArn should be configured for subscriptions as part of this stacks provisioning. See http://docs.aws.amazon.com/lambda/latest/dg/intro-core-components.html#intro-core-components-event-sources for more information.
Example ¶
package main import ( "encoding/json" "net/http" "github.com/Sirupsen/logrus" ) const snsTopic = "arn:aws:sns:us-west-2:123412341234:mySNSTopic" func snsProcessor(event *json.RawMessage, context *LambdaContext, w http.ResponseWriter, logger *logrus.Logger) { logger.WithFields(logrus.Fields{ "RequestID": context.AWSRequestID, }).Info("SNSEvent") logger.Info("Event data: ", string(*event)) } func main() { var lambdaFunctions []*LambdaAWSInfo snsLambda := NewLambda(IAMRoleDefinition{}, snsProcessor, nil) snsLambda.Permissions = append(snsLambda.Permissions, SNSPermission{ BasePermission: BasePermission{ SourceArn: snsTopic, }, }) lambdaFunctions = append(lambdaFunctions, snsLambda) Main("SNSLambdaApp", "Registers for SNS events", lambdaFunctions, nil, nil) }
Output:
type Stage ¶
type Stage struct { CacheClusterEnabled bool CacheClusterSize string Description string Variables map[string]string // contains filtered or unexported fields }
Stage proxies the AWS SDK's Stage data. See http://docs.aws.amazon.com/sdk-for-go/api/service/apigateway.html#type-Stage
func NewStage ¶
NewStage returns a Stage object with the given name. Providing a Stage value to NewAPIGateway implies that the API Gateway resources should be deployed (eg: made publicly accessible). See http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-deploy-api.html
type TemplateDecorator ¶
type TemplateDecorator func(serviceName string, lambdaResourceName string, lambdaResource gocf.LambdaFunction, resourceMetadata map[string]interface{}, S3Bucket string, S3Key string, buildID string, template *gocf.Template, context map[string]interface{}, logger *logrus.Logger) error
TemplateDecorator allows Lambda functions to annotate the CloudFormation template definition. Both the resources and the outputs params are initialized to an empty ArbitraryJSONObject and should be populated with valid CloudFormation ArbitraryJSONObject values. The CloudFormationResourceName() function can be used to generate logical CloudFormation-compatible resource names. See http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html and http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html for more information.
type WorkflowHook ¶
type WorkflowHook func(context map[string]interface{}, serviceName string, S3Bucket string, buildID string, awsSession *session.Session, noop bool, logger *logrus.Logger) error
WorkflowHook defines a user function that should be called at a specific point in the larger Sparta workflow. The first argument is a map that is shared across all LifecycleHooks and which Sparta treats as an opaque value.
type WorkflowHooks ¶
type WorkflowHooks struct { // PreBuild is called before the current Sparta-binary is compiled PreBuild WorkflowHook // PostBuild is called after the current Sparta-binary is compiled PostBuild WorkflowHook // ArchiveHook is called after Sparta has populated the ZIP archive containing the // AWS Lambda code package and before the ZIP writer is closed. Define this hook // to add additional resource files to your Lambda package Archive ArchiveHook // PreMarshall is called before Sparta marshalls the application contents to a CloudFormation template PreMarshall WorkflowHook // PostMarshall is called after Sparta marshalls the application contents to a CloudFormation template PostMarshall WorkflowHook // Rollback is called if there is an error performing the requested operation Rollback RollbackHook }
WorkflowHooks is a structure that allows callers to customize the Sparta provisioning pipeline to add contents the Lambda archive or perform other workflow operations.
Example ¶
package main import ( "archive/zip" "encoding/json" "fmt" "io" "github.com/Sirupsen/logrus" "github.com/aws/aws-sdk-go/aws/session" "net/http" "strings" ) const userdataResourceContents = ` { "Hello" : "World", }` // Standard AWS λ function func helloZipLambda(event *json.RawMessage, context *LambdaContext, w http.ResponseWriter, logger *logrus.Logger) { fmt.Fprint(w, "Hello World") } func archiveHook(context map[string]interface{}, serviceName string, zipWriter *zip.Writer, awsSession *session.Session, noop bool, logger *logrus.Logger) error { logger.Info("Adding userResource") resourceFileName := "userResource.json" binaryWriter, binaryWriterErr := zipWriter.Create(resourceFileName) if nil != binaryWriterErr { return binaryWriterErr } userdataReader := strings.NewReader(userdataResourceContents) _, copyErr := io.Copy(binaryWriter, userdataReader) return copyErr } func main() { workflowHooks := WorkflowHooks{ Archive: archiveHook, } var lambdaFunctions []*LambdaAWSInfo helloWorldLambda := NewLambda("PreexistingAWSLambdaRoleName", mainHelloWorld, nil) lambdaFunctions = append(lambdaFunctions, helloWorldLambda) MainEx("HelloWorldArchiveHook", "Description for Hello World HelloWorldArchiveHook", lambdaFunctions, nil, nil, &workflowHooks) }
Output:
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
cloudformation
Package cloudformation scopes CloudFormation-specific utiltities for Sparta
|
Package cloudformation scopes CloudFormation-specific utiltities for Sparta |
cloudwatchlogs
Package cloudwatchlogs scopes CloudWatchLogs-specific utiltities for Sparta
|
Package cloudwatchlogs scopes CloudWatchLogs-specific utiltities for Sparta |
dynamodb
Package dynamodb provides types to support unmarshalling generic `event *json.RawMessage` types into DynamoDB specific event structures.
|
Package dynamodb provides types to support unmarshalling generic `event *json.RawMessage` types into DynamoDB specific event structures. |
kinesis
Package kinesis provides types to support unmarshalling generic `event *json.RawMessage` types into Kinesis specific event structures.
|
Package kinesis provides types to support unmarshalling generic `event *json.RawMessage` types into Kinesis specific event structures. |
s3
Package s3 provides types to support unmarshalling generic `event *json.RawMessage` types into S3 specific event structures.
|
Package s3 provides types to support unmarshalling generic `event *json.RawMessage` types into S3 specific event structures. |
sns
Package sns provides types to support unmarshalling generic `event *json.RawMessage` types into SNS specific event structures.
|
Package sns provides types to support unmarshalling generic `event *json.RawMessage` types into SNS specific event structures. |
Package explore scopes types that are used for the Sparta `explore` command line option.
|
Package explore scopes types that are used for the Sparta `explore` command line option. |
resources
|
|