sparta

package module
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 3, 2018 License: MIT Imports: 63 Imported by: 0

README

Sparta

Build Status

GoDoc

Go Report Card

Visit gosparta.io for complete documentation.

Overview

Sparta takes a set of golang functions and automatically provisions them in AWS Lambda as a logical unit.

AWS Lambda functions are defined using the standard AWS Lambda signatures:

  • func()
  • func() error
  • func(TIn) error
  • func() (TOut, error)
  • func(context.Context) error
  • func(context.Context, TIn) error
  • func(context.Context) (TOut, error)
  • func(context.Context, TIn) (TOut, error)

The TIn and TOut parameters represent encoding/json un/marshallable types.

For instance:

// Standard AWS λ function
func helloWorld(ctx context.Context) (string, error) {
  ...
}

where

  • ctx : The request context that includes Sparta both the AWS Context as well as Sparta specific values

Consumers define a set of lambda functions and provide them to Sparta to create a self-documenting, self-deploying AWS Lambda binary:

	lambdaFn := sparta.HandleAWSLambda("Hello World",
		helloWorld,
		sparta.IAMRoleDefinition{})

	var lambdaFunctions []*sparta.LambdaAWSInfo
	lambdaFunctions = append(lambdaFunctions, lambdaFn)

	err := sparta.Main("HelloWorldStack",
		"My Hello World stack",
		lambdaFunctions,
		nil,
		nil)

Given a set of registered golang functions, Sparta will:

  • Either verify or provision the defined IAM roles
  • Build a deployable application via Provision()
  • Zip the contents and associated proxying logic
  • Dynamically create a CloudFormation template to either create or update the service state.
  • Optionally:
    • Register with S3 and SNS for push source configuration
    • Provision an API Gateway service to make your functions publicly available
    • Provision an S3 static website

Visit gosparta.io for complete documentation.

Contributors

Thanks to all Sparta contributors (alphabetical)

Documentation

Index

Examples

Constants

View Source
const (
	// ContextKeyLogger is the request-independent *logrus.Logger
	// instance common to all requests
	ContextKeyLogger contextKey = iota
	// ContextKeyRequestLogger is the *logrus.Entry instance
	// that is annotated with request-identifying
	// information extracted from the AWS context object
	ContextKeyRequestLogger
	// ContextKeyLambdaContext is the *sparta.LambdaContext
	// pointer in the request
	// DEPRECATED
	ContextKeyLambdaContext
)
View Source
const (
	// SpartaVersion defines the current Sparta release
	SpartaVersion = "1.3.0"
	// GoLambdaVersion is the Go version runtime used for the lambda function
	GoLambdaVersion = "go1.x"
	// SpartaBinaryName is binary name that exposes the Go lambda function
	SpartaBinaryName = "Sparta.lambda.amd64"
)
View Source
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

View Source
const (
	// ContextKeyLambdaVersions is the key in the context that stores the map
	// of autoincrementing versions
	ContextKeyLambdaVersions = "spartaLambdaVersions"
)
View Source
const (
	// OutputAPIGatewayURL is the keyname used in the CloudFormation Output
	// that stores the APIGateway provisioned URL
	// @enum OutputKey
	OutputAPIGatewayURL = "APIGatewayURL"
)
View Source
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"
)
View Source
const (
	// ScratchDirectory is the cwd relative path component
	// where intermediate build artifacts are created
	ScratchDirectory = ".sparta"
)
View Source
const SpartaGitHash = "a0e35ebaba4a0efec216359a22ca9572fad02af8"

SpartaGitHash is the commit hash of this Sparta library

Variables

View Source
var (
	// SpartaTagBuildIDKey is the keyname used in the CloudFormation Output
	// that stores the user-supplied or automatically generated BuildID
	// for this run
	SpartaTagBuildIDKey = spartaTagName("buildId")

	// SpartaTagBuildTagsKey is the keyname used in the CloudFormation Output
	// that stores the optional user-supplied golang build tags
	SpartaTagBuildTagsKey = spartaTagName("buildTags")
)
View Source
var AssumePolicyDocument = ArbitraryJSONObject{
	"Version": "2012-10-17",
	"Statement": []ArbitraryJSONObject{
		{
			"Effect": "Allow",
			"Principal": ArbitraryJSONObject{
				"Service": []string{LambdaPrincipal,
					EC2Principal,
					APIGatewayPrincipal},
			},
			"Action": []string{"sts:AssumeRole"},
		},
	},
}

AssumePolicyDocument defines common a IAM::Role PolicyDocument used as part of IAM::Role resource definitions

View Source
var CommandLineOptions = struct {
	Root      *cobra.Command
	Version   *cobra.Command
	Provision *cobra.Command
	Delete    *cobra.Command
	Execute   *cobra.Command
	Describe  *cobra.Command
	Explore   *cobra.Command
	Profile   *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.

View Source
var CommonIAMStatements = struct {
	Core     []spartaIAM.PolicyStatement
	VPC      []spartaIAM.PolicyStatement
	DynamoDB []spartaIAM.PolicyStatement
	Kinesis  []spartaIAM.PolicyStatement
	SQS      []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...),
		},

		{
			Effect: "Allow",
			Action: []string{"xray:PutTraceSegments",
				"xray:PutTelemetryRecords"},
			Resource: gocf.String("*"),
		},
	},
	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",
			},
		},
	},

	SQS: []spartaIAM.PolicyStatement{
		{
			Effect: "Allow",
			Action: []string{"SQS:GetQueueAttributes",
				"SQS:ChangeMessageVisibility",
				"SQS:DeleteMessage",
				"SQS:ReceiveMessage",
			},
		},
	},
}

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.

View Source
var OptionsGlobal optionsGlobalStruct

OptionsGlobal stores the global command line options

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

View Source
var StampedBuildID string

StampedBuildID is the buildID stamped into the binary. For the case of a local build this is set by the provision command and the same value is stamped into the cross compiled binary at AWS Lambda execution time

Functions

func CloudFormationResourceName

func CloudFormationResourceName(prefix string, parts ...string) string

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

func Delete(serviceName string, logger *logrus.Logger) error

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,
	s3BucketName string,
	buildTags string,
	linkFlags string,
	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(serviceName string,
	lambdaAWSInfos []*LambdaAWSInfo,
	logger *logrus.Logger) error

Execute creates an HTTP listener to dispatch execution. Typically called via Main() via command line arguments.

func Explore

func Explore(serviceName string,
	serviceDescription string,
	lambdaAWSInfos []*LambdaAWSInfo,
	api *API,
	site *S3Site,
	s3BucketName string,
	buildTags string,
	linkerFlags string,
	logger *logrus.Logger) error

Explore is an interactive command that brings up a GUI to test lambda functions previously deployed into AWS lambda. It's not supported in the AWS binary build

func IsExecutingInLambda added in v1.3.0

func IsExecutingInLambda() bool

IsExecutingInLambda is a utility function to return a boolean indicating whether the application is running in AWS Lambda. See the list of environment variables defined at: https://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html for more information.

func LambdaName added in v1.3.0

func LambdaName(handlerSymbol interface{}) string

LambdaName returns the Go-reflection discovered name for a given function

func Logger added in v1.3.0

func Logger() *logrus.Logger

Logger returns the sparta Logger instance for this process

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 (
	"context"
	"net/http"

	"github.com/aws/aws-lambda-go/lambdacontext"
	"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(ctx context.Context,
	props map[string]interface{}) error {
	lambdaCtx, _ := lambdacontext.FromContext(ctx)
	Logger().WithFields(logrus.Fields{
		"RequestID":  lambdaCtx.AwsRequestID,
		"Properties": props,
	}).Info("Lambda event")
	return nil
}

// 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 := HandleAWSLambda(LambdaName(echoAPIGatewayEvent),
		echoAPIGatewayEvent,
		IAMRoleDefinition{})

	// 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", http.StatusOK)

	// 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 (
	"context"
	"net/http"

	"github.com/aws/aws-lambda-go/lambdacontext"
	"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(ctx context.Context,
	props map[string]interface{}) error {
	lambdaCtx, _ := lambdacontext.FromContext(ctx)
	Logger().WithFields(logrus.Fields{
		"RequestID":  lambdaCtx.AwsRequestID,
		"Properties": props,
	}).Info("Lambda event")
	return nil
}

// 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 := HandleAWSLambda(LambdaName(echoAPIGatewayHTTPEvent),
		echoAPIGatewayHTTPEvent,
		IAMRoleDefinition{})

	// 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", http.StatusOK)
	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 "context"

// 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(ctx context.Context) (string, error) {
	return "Hello World!", nil
}

func main() {
	var lambdaFunctions []*LambdaAWSInfo
	helloWorldLambda := HandleAWSLambda("PreexistingAWSLambdaRoleName",
		mainHelloWorld,
		IAMRoleDefinition{})

	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 (
	"context"
	"net/http"

	"github.com/aws/aws-lambda-go/lambdacontext"
	"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(ctx context.Context,
	props map[string]interface{}) (map[string]interface{}, error) {
	lambdaCtx, _ := lambdacontext.FromContext(ctx)
	Logger().WithFields(logrus.Fields{
		"RequestID":  lambdaCtx.AwsRequestID,
		"Properties": props,
	}).Info("Lambda event")
	return props, nil
}

// 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 := HandleAWSLambda(LambdaName(echoS3SiteAPIGatewayEvent),
		echoS3SiteAPIGatewayEvent,
		IAMRoleDefinition{})
	apiGatewayResource, _ := apiGateway.NewResource("/hello", echoS3SiteAPIGatewayEventLambdaFn)
	_, err := apiGatewayResource.NewMethod("GET", http.StatusOK)
	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,
	useCGO bool) error

MainEx provides an "extended" Main that supports customizing the standard Sparta workflow via the `workflowHooks` parameter.

func NewLogger

func NewLogger(level string) (*logrus.Logger, error)

NewLogger returns a new logrus.Logger instance. It is the caller's responsibility to set the formatter if needed.

func NewLoggerWithFormatter added in v1.3.0

func NewLoggerWithFormatter(level string, formatter logrus.Formatter) (*logrus.Logger, error)

NewLoggerWithFormatter returns a logger with the given formatter. If formatter is nil, a TTY-aware formatter is used

func ParseOptions

func ParseOptions(handler CommandLineOptionsHook) error

ParseOptions the command line options

Example
package main

import (
	"fmt"
	"os"

	"github.com/pkg/errors"
	"github.com/spf13/cobra"
	"gopkg.in/go-playground/validator.v9"
)

var exampleValidator *validator.Validate

// 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 `validate:"required"`
	Password   string `validate:"required"`
	SSHKeyName string `validate:"-"`
}

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 errors.Errorf("SSHKeyName option is required")
		}
		fmt.Printf("Command: %s\n", command.Name())
		switch command.Name() {
		case "provision",
			"sync":
			validationErr := exampleValidator.Struct(options)
			return errors.Wrapf(validationErr, "Validating input")
		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 Profile added in v1.3.0

func Profile(serviceName string,
	serviceDescription string,
	s3BucketName string,
	httpPort int,
	logger *logrus.Logger) error

Profile is the interactive command used to pull S3 assets locally into /tmp and run ppro against the cached profiles

func Provision

func Provision(noop bool,
	serviceName string,
	serviceDescription string,
	lambdaAWSInfos []*LambdaAWSInfo,
	api *API,
	site *S3Site,
	s3Bucket string,
	useCGO bool,
	inPlaceUpdates bool,
	buildID string,
	codePipelineTrigger string,
	buildTags string,
	linkerFlags 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.

func RegisterCodePipelineEnvironment added in v1.3.0

func RegisterCodePipelineEnvironment(environmentName string,
	environmentVariables map[string]string) error

RegisterCodePipelineEnvironment is part of a CodePipeline deployment and defines the environments available for deployment. Environments are defined the `environmentName`. The values defined in the environmentVariables are made available to each service as environment variables. The environment key will be transformed into a configuration file for a CodePipeline CloudFormation action: TemplateConfiguration: !Sub "TemplateSource::${environmentName}".

func ScheduleProfileLoop added in v1.3.0

func ScheduleProfileLoop(s3BucketArchive interface{},
	snapshotInterval time.Duration,
	cpuProfileDuration time.Duration,
	profileNames ...string)

ScheduleProfileLoop installs a profiling loop that pushes profile information to S3 for local consumption using a `profile` command that wraps pprof

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
	// CORS options - if non-nil, supersedes CORSEnabled
	CORSOptions *CORSOptions
	// 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

func NewAPIGateway(name string, stage *Stage) *API

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) LogicalResourceName added in v1.3.0

func (api *API) LogicalResourceName() string

LogicalResourceName returns the CloudFormation logical resource name for this API

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 ArchiveHookFunc added in v1.3.0

type ArchiveHookFunc func(context map[string]interface{},
	serviceName string,
	zipWriter *zip.Writer,
	awsSession *session.Session,
	noop bool,
	logger *logrus.Logger) error

ArchiveHookFunc is the adapter to transform an existing ArchiveHook into a WorkflowHookHandler satisfier

func (ArchiveHookFunc) DecorateArchive added in v1.3.0

func (ahf ArchiveHookFunc) DecorateArchive(context map[string]interface{},
	serviceName string,
	zipWriter *zip.Writer,
	awsSession *session.Session,
	noop bool,
	logger *logrus.Logger) error

DecorateArchive calls whf(...) to satisfy ArchiveHookHandler

type ArchiveHookHandler added in v1.3.0

type ArchiveHookHandler interface {
	DecorateArchive(context map[string]interface{},
		serviceName string,
		zipWriter *zip.Writer,
		awsSession *session.Session,
		noop bool,
		logger *logrus.Logger) error
}

ArchiveHookHandler is the interface type to indicate a workflow hook

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 CORSOptions added in v1.3.0

type CORSOptions struct {
	// Headers represent the CORS headers that should be used for an OPTIONS
	// preflight request. These should be of the form key-value as in:
	// "Access-Control-Allow-Headers"="Content-Type,X-Amz-Date,Authorization,X-Api-Key"
	Headers map[string]interface{}
}

CORSOptions is a struct that clients supply to the API in order to enable and parameterize CORS API values

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 (
	"context"

	"github.com/aws/aws-lambda-go/lambdacontext"
	"github.com/sirupsen/logrus"
)

func cloudWatchEventProcessor(ctx context.Context,
	event map[string]interface{}) (map[string]interface{}, error) {

	lambdaCtx, _ := lambdacontext.FromContext(ctx)
	Logger().WithFields(logrus.Fields{
		"RequestID": lambdaCtx.AwsRequestID,
	}).Info("Request received")
	Logger().Info("CloudWatch Event received")
	return nil, nil
}

func main() {
	cloudWatchEventsLambda := HandleAWSLambda(LambdaName(cloudWatchEventProcessor),
		cloudWatchEventProcessor,
		IAMRoleDefinition{})

	cloudWatchEventsPermission := CloudWatchEventsPermission{}
	cloudWatchEventsPermission.Rules = make(map[string]CloudWatchEventsRule)
	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

type CloudWatchEventsRuleTarget struct {
	Input     string
	InputPath string
}

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 (
	"context"

	"github.com/aws/aws-lambda-go/lambdacontext"
	"github.com/sirupsen/logrus"
)

func cloudWatchLogsProcessor(ctx context.Context,
	props map[string]interface{}) error {
	lambdaCtx, _ := lambdacontext.FromContext(ctx)
	Logger().WithFields(logrus.Fields{
		"RequestID": lambdaCtx.AwsRequestID,
	}).Info("CloudWatch log event")
	Logger().Info("CloudWatch Log event received")
	return nil
}

func main() {
	var lambdaFunctions []*LambdaAWSInfo

	cloudWatchLogsLambda := HandleAWSLambda(LambdaName(cloudWatchLogsProcessor),
		cloudWatchLogsProcessor,
		IAMRoleDefinition{})

	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

type CloudWatchLogsSubscriptionFilter struct {
	FilterPattern string
	LogGroupName  string
}

CloudWatchLogsSubscriptionFilter represents the CloudWatch Log filter information

type CommandLineOptionsHook

type CommandLineOptionsHook func(command *cobra.Command) error

CommandLineOptionsHook allows embedding applications the ability to validate caller-defined command line arguments. Return an error if the command line fails.

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. It's a reflection-based pass-through to DiscoverByName

type DiscoveryResource

type DiscoveryResource struct {
	ResourceID   string
	ResourceRef  string
	ResourceType string
	Properties   map[string]string
}

DiscoveryResource stores information about a CloudFormation resource that the calling Go function `DependsOn`.

type EventSourceMapping

type EventSourceMapping struct {
	StartingPosition string
	EventSourceArn   interface{}
	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#Integration

type IntegrationResponse

type IntegrationResponse struct {
	Parameters       map[string]interface{} `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/#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 decorators. If non empty, the decorators will be called,
	// in order, to annotate the template
	Decorators []TemplateDecoratorHandler
	// 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 HandleAWSLambda added in v1.3.0

func HandleAWSLambda(functionName string,
	lambdaHandler interface{},
	roleNameOrIAMRoleDefinition interface{}) *LambdaAWSInfo

HandleAWSLambda registers lambdaHandler with the given functionName using the default lambdaFunctionOptions

Example (IAMRoleDefinition)
package main

import (
	"context"
	"fmt"

	"github.com/aws/aws-lambda-go/lambdacontext"
	"github.com/sirupsen/logrus"
)

func lambdaHelloWorld2(ctx context.Context,
	props map[string]interface{}) error {
	lambdaCtx, _ := lambdacontext.FromContext(ctx)
	Logger().WithFields(logrus.Fields{
		"RequestID": lambdaCtx.AwsRequestID,
	}).Info("Lambda event")
	Logger().Info("Event received")
	return nil
}
func main() {
	roleDefinition := IAMRoleDefinition{}
	roleDefinition.Privileges = append(roleDefinition.Privileges, IAMRolePrivilege{
		Actions: []string{"s3:GetObject",
			"s3:PutObject"},
		Resource: "arn:aws:s3:::*",
	})
	helloWorldLambda := HandleAWSLambda(LambdaName(lambdaHelloWorld2),
		lambdaHelloWorld2,
		IAMRoleDefinition{})
	if nil != helloWorldLambda {
		fmt.Printf("Failed to create new Lambda function")
	}
}
Output:

Example (PreexistingIAMRoleName)
package main

import (
	"fmt"
	"net/http"
)

func lambdaHelloWorld(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello World!")
}

func main() {
	helloWorldLambda := HandleAWSLambda(LambdaName(lambdaHelloWorld),
		lambdaHelloWorld,
		IAMRoleDefinition{})
	if nil != helloWorldLambda {
		fmt.Printf("Failed to create new Lambda function")
	}
}
Output:

func (*LambdaAWSInfo) LogicalResourceName added in v1.3.0

func (info *LambdaAWSInfo) LogicalResourceName() string

LogicalResourceName returns the stable, content-addressable logical name for this LambdaAWSInfo value. This is the CloudFormation resource name

func (*LambdaAWSInfo) RequireCustomResource

func (info *LambdaAWSInfo) RequireCustomResource(roleNameOrIAMRoleDefinition interface{},
	handlerSymbol interface{},
	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 (
	"context"

	"github.com/aws/aws-lambda-go/lambdacontext"
	awsLambdaCtx "github.com/aws/aws-lambda-go/lambdacontext"
	spartaCFResources "github.com/mweagle/Sparta/aws/cloudformation/resources"
	gocf "github.com/mweagle/go-cloudformation"
	"github.com/sirupsen/logrus"
)

// Standard AWS λ function
func helloWorld(ctx context.Context,
	props map[string]interface{}) (string, error) {
	lambdaCtx, _ := lambdacontext.FromContext(ctx)
	Logger().WithFields(logrus.Fields{
		"RequestID":  lambdaCtx.AwsRequestID,
		"Properties": props,
	}).Info("Lambda event")
	return "Event processed", nil
}

// User defined λ-backed CloudFormation CustomResource
func userDefinedCustomResource(ctx context.Context,
	event spartaCFResources.CloudFormationLambdaEvent) (map[string]interface{}, error) {

	logger, _ := ctx.Value(ContextKeyLogger).(*logrus.Logger)
	lambdaCtx, _ := awsLambdaCtx.FromContext(ctx)

	var opResults = map[string]interface{}{
		"CustomResourceResult": "Victory!",
	}

	opErr := spartaCFResources.SendCloudFormationResponse(lambdaCtx,
		&event,
		opResults,
		nil,
		logger)
	return opResults, opErr
}

func main() {

	lambdaFn := HandleAWSLambda(LambdaName(helloWorld),
		helloWorld,
		IAMRoleDefinition{})

	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:

type LambdaContext

type LambdaContext struct {
	FunctionName       string `json:"functionName"`
	FunctionVersion    string `json:"functionVersion"`
	InvokedFunctionARN string `json:"invokedFunctionArn"`
	MemoryLimitInMB    string `json:"memoryLimitInMB"`
	AWSRequestID       string `json:"awsRequestId"`
	LogGroupName       string `json:"logGroupName"`
	LogStreamName      string `json:"logStreamName"`
}

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
	// Environment Variables
	Environment map[string]*gocf.StringExpr
	// KMS Key Arn used to encrypt environment variables
	KmsKeyArn string
	// The maximum of concurrent executions you want reserved for the function
	ReservedConcurrentExecutions int64
	// DeadLetterConfigArn is how Lambda handles events that it can't process.If
	// you don't specify a Dead Letter Queue (DLQ) configuration, Lambda
	// discards events after the maximum number of retries. For more information,
	// see Dead Letter Queues in the AWS Lambda Developer Guide.
	DeadLetterConfigArn gocf.Stringable
	// Tags to associate with the Lambda function
	Tags map[string]string
	// Tracing options for XRay
	TracingConfig *gocf.LambdaFunctionTracingConfig
	// Additional params
	SpartaOptions *SpartaOptions
}

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

	// Supported HTTP request Content-Types. Used to limit the amount of VTL
	// injected into the CloudFormation template. Eligible values include:
	// application/json
	// text/plain
	// application/x-www-form-urlencoded
	// multipart/form-data
	SupportedRequestContentTypes []string

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

type Resource struct {
	Methods map[string]*Method
	// contains filtered or unexported fields
}

Resource proxies the AWS SDK's Resource data. See http://docs.aws.amazon.com/sdk-for-go/api/service/apigateway.html#type-Resource

func (*Resource) NewAuthorizedMethod

func (resource *Resource) NewAuthorizedMethod(httpMethod string,
	authorizerID gocf.Stringable,
	defaultHTTPStatusCode int,
	possibleHTTPStatusCodeResponses ...int) (*Method, error)

NewAuthorizedMethod associates the httpMethod name and authorizationID with the given Resource. The authorizerID param is a cloudformation.Strinable satisfying value

func (*Resource) NewMethod

func (resource *Resource) NewMethod(httpMethod string,
	defaultHTTPStatusCode int,
	possibleHTTPStatusCodeResponses ...int) (*Method, error)

NewMethod associates the httpMethod name with the given Resource. The returned Method has no authorization requirements. To limit the amount of API gateway resource mappings, supply the variadic slice of possibleHTTPStatusCodeResponses which is the universe of all HTTP status codes returned by your Sparta function. If this slice is non-empty, Sparta will *ONLY* generate mappings for known codes. This slice need only include the codes in addition to the defaultHTTPStatusCode. If the function can only return a single value, provide the defaultHTTPStatusCode in the possibleHTTPStatusCodeResponses slice

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#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 RollbackHookFunc added in v1.3.0

type RollbackHookFunc func(context map[string]interface{},
	serviceName string,
	awsSession *session.Session,
	noop bool,
	logger *logrus.Logger)

RollbackHookFunc the adapter to transform an existing RollbackHook into a RollbackHookHandler satisfier

func (RollbackHookFunc) Rollback added in v1.3.0

func (rhf RollbackHookFunc) Rollback(context map[string]interface{},
	serviceName string,
	awsSession *session.Session,
	noop bool,
	logger *logrus.Logger) error

Rollback calls sdhf(...) to satisfy ArchiveHookHandler

type RollbackHookHandler added in v1.3.0

type RollbackHookHandler interface {
	Rollback(context map[string]interface{},
		serviceName string,
		awsSession *session.Session,
		noop bool,
		logger *logrus.Logger) error
}

RollbackHookHandler is the interface type to indicate a workflow hook

type RuntimeLoggerHook added in v1.3.0

type RuntimeLoggerHook func(context map[string]interface{},
	serviceName string,
	logger *logrus.Logger) error

RuntimeLoggerHook is responsible for adding custom hooks to the Logrus logger for things like publishing to StackDriver

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 (
	"context"

	"github.com/aws/aws-lambda-go/lambdacontext"
	"github.com/sirupsen/logrus"
)

const s3Bucket = "arn:aws:sns:us-west-2:123412341234:myBucket"

func s3LambdaProcessor(ctx context.Context,
	props map[string]interface{}) (map[string]interface{}, error) {
	lambdaCtx, _ := lambdacontext.FromContext(ctx)
	Logger().WithFields(logrus.Fields{
		"RequestID":  lambdaCtx.AwsRequestID,
		"Properties": props,
	}).Info("Lambda event")
	return props, nil
}

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 := HandleAWSLambda(LambdaName(s3LambdaProcessor),
		s3LambdaProcessor,
		IAMRoleDefinition{})

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

func NewS3Site

func NewS3Site(resources string) (*S3Site, error)

NewS3Site returns a new S3Site pointer initialized with the static resources at the supplied path. If resources is a directory, the contents will be recursively archived and used to populate the new S3 bucket.

func (*S3Site) CloudFormationS3ResourceName added in v1.3.0

func (s3Site *S3Site) CloudFormationS3ResourceName() string

CloudFormationS3ResourceName returns the stable CloudformationResource name that can be used by callers to get S3 resource outputs for API Gateway configuration

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 := HandleAWSLambda(LambdaName(sesLambdaProcessor),
	sesLambdaProcessor,
	roleDefinition)

// 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 := HandleAWSLambda(LambdaName(sesLambdaProcessor),
	sesLambdaProcessor,
	roleDefinition)

// 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 (
	"context"

	"github.com/aws/aws-lambda-go/lambdacontext"
	"github.com/sirupsen/logrus"
)

const snsTopic = "arn:aws:sns:us-west-2:123412341234:mySNSTopic"

func snsProcessor(ctx context.Context,
	props map[string]interface{}) (map[string]interface{}, error) {
	lambdaCtx, _ := lambdacontext.FromContext(ctx)
	Logger().WithFields(logrus.Fields{
		"RequestID":  lambdaCtx.AwsRequestID,
		"Properties": props,
	}).Info("Lambda event")
	return props, nil
}

func main() {
	var lambdaFunctions []*LambdaAWSInfo

	snsLambda := HandleAWSLambda(LambdaName(snsProcessor),
		snsProcessor,
		IAMRoleDefinition{})
	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 ServiceDecoratorHook added in v1.3.0

type ServiceDecoratorHook func(context map[string]interface{},
	serviceName string,
	template *gocf.Template,
	S3Bucket string,
	buildID string,
	awsSession *session.Session,
	noop bool,
	logger *logrus.Logger) error

ServiceDecoratorHook defines a user function that is called a single time in the marshall workflow.

type ServiceDecoratorHookFunc added in v1.3.0

type ServiceDecoratorHookFunc func(context map[string]interface{},
	serviceName string,
	template *gocf.Template,
	S3Bucket string,
	buildID string,
	awsSession *session.Session,
	noop bool,
	logger *logrus.Logger) error

ServiceDecoratorHookFunc is the adapter to transform an existing ArchiveHook into a WorkflowHookHandler satisfier

func (ServiceDecoratorHookFunc) DecorateService added in v1.3.0

func (sdhf ServiceDecoratorHookFunc) DecorateService(context map[string]interface{},
	serviceName string,
	template *gocf.Template,
	S3Bucket string,
	buildID string,
	awsSession *session.Session,
	noop bool,
	logger *logrus.Logger) error

DecorateService calls sdhf(...) to satisfy ArchiveHookHandler

type ServiceDecoratorHookHandler added in v1.3.0

type ServiceDecoratorHookHandler interface {
	DecorateService(context map[string]interface{},
		serviceName string,
		template *gocf.Template,
		S3Bucket string,
		buildID string,
		awsSession *session.Session,
		noop bool,
		logger *logrus.Logger) error
}

ServiceDecoratorHookHandler is the interface type to indicate a workflow hook

type SpartaOptions added in v1.3.0

type SpartaOptions struct {
	// User supplied function name to use for
	// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html#cfn-lambda-function-functionname
	// value. If this is not supplied, a reflection-based
	// name will be automatically used.
	Name string
}

SpartaOptions allow the passing in of additional options during the creation of a Lambda Function

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

func NewStage(name string) *Stage

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.

func LambdaVersioningDecorator added in v1.3.0

func LambdaVersioningDecorator() TemplateDecorator

LambdaVersioningDecorator returns a TemplateDecorator that is responsible for including a versioning resource with the given lambda function

type TemplateDecoratorHandler added in v1.3.0

type TemplateDecoratorHandler interface {
	DecorateTemplate(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
}

TemplateDecoratorHandler is the interface type to indicate a template decoratorHook

type TemplateDecoratorHookFunc added in v1.3.0

type TemplateDecoratorHookFunc 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

TemplateDecoratorHookFunc is the adapter to transform an existing ArchiveHook into a WorkflowHookHandler satisfier

func (TemplateDecoratorHookFunc) DecorateTemplate added in v1.3.0

func (tdhf TemplateDecoratorHookFunc) DecorateTemplate(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

DecorateTemplate calls tdhf(...) to satisfy TemplateDecoratorHandler

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 WorkflowHookFunc added in v1.3.0

type WorkflowHookFunc func(context map[string]interface{},
	serviceName string,
	S3Bucket string,
	buildID string,
	awsSession *session.Session,
	noop bool,
	logger *logrus.Logger) error

WorkflowHookFunc is the adapter to transform an existing WorkflowHook into a WorkflowHookHandler satisfier

func (WorkflowHookFunc) DecorateWorkflow added in v1.3.0

func (whf WorkflowHookFunc) DecorateWorkflow(context map[string]interface{},
	serviceName string,
	S3Bucket string,
	buildID string,
	awsSession *session.Session,
	noop bool,
	logger *logrus.Logger) error

DecorateWorkflow calls whf(...) to satisfy WorkflowHookHandler

type WorkflowHookHandler added in v1.3.0

type WorkflowHookHandler interface {
	DecorateWorkflow(context map[string]interface{},
		serviceName string,
		S3Bucket string,
		buildID string,
		awsSession *session.Session,
		noop bool,
		logger *logrus.Logger) error
}

WorkflowHookHandler is the interface type to indicate a workflow hook

type WorkflowHooks

type WorkflowHooks struct {
	// Initial hook context. May be empty
	Context map[string]interface{}
	// PreBuild is called before the current Sparta-binary is compiled
	PreBuild WorkflowHook
	// PreBuilds are called before the current Sparta-binary is compiled
	PreBuilds []WorkflowHookHandler
	// PostBuild is called after the current Sparta-binary is compiled
	PostBuild WorkflowHook
	// PostBuilds are called after the current Sparta-binary is compiled
	PostBuilds []WorkflowHookHandler
	// 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
	// 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
	Archives []ArchiveHookHandler
	// PreMarshall is called before Sparta marshalls the application contents to a CloudFormation template
	PreMarshall WorkflowHook
	// PreMarshalls are called before Sparta marshalls the application contents into a CloudFormation
	// template
	PreMarshalls []WorkflowHookHandler
	// ServiceDecorator is called before Sparta marshalls the CloudFormation template
	ServiceDecorator ServiceDecoratorHook
	// ServiceDecorators are called before Sparta marshalls the CloudFormation template
	ServiceDecorators []ServiceDecoratorHookHandler
	// PostMarshall is called after Sparta marshalls the application contents to a CloudFormation template
	PostMarshall WorkflowHook
	// PostMarshalls are called after Sparta marshalls the application contents to a CloudFormation
	// template
	PostMarshalls []WorkflowHookHandler

	// Rollback is called if there is an error performing the requested operation
	Rollback RollbackHook
	// Rollbacks are called if there is an error performing the requested operation
	Rollbacks []RollbackHookHandler

	// Allow minimal customization of the runtime logger
	RuntimeLoggerHook RuntimeLoggerHook
}

WorkflowHooks is a structure that allows callers to customize the Sparta provisioning pipeline to add contents the Lambda archive or perform other workflow operations. TODO: remove single-valued fields

Example
package main

import (
	"archive/zip"
	"context"
	"io"

	"strings"

	"github.com/aws/aws-lambda-go/lambdacontext"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/sirupsen/logrus"
)

const userdataResourceContents = `
{
  "Hello" : "World",
}`

func helloZipLambda(ctx context.Context,
	props map[string]interface{}) (string, error) {
	lambdaCtx, _ := lambdacontext.FromContext(ctx)
	Logger().WithFields(logrus.Fields{
		"RequestID":  lambdaCtx.AwsRequestID,
		"Properties": props,
	}).Info("Lambda event")
	return "Event processed", nil
}

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 := HandleAWSLambda("PreexistingAWSLambdaRoleName",
		helloZipLambda,
		nil)
	lambdaFunctions = append(lambdaFunctions, helloWorldLambda)
	MainEx("HelloWorldArchiveHook",
		"Description for Hello World HelloWorldArchiveHook",
		lambdaFunctions,
		nil,
		nil,
		&workflowHooks,
		false)
}
Output:

Directories

Path Synopsis
aws
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.
iam
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.
ses
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.
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL