sparta

package module
Version: v1.15.0 Latest Latest
Warning

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

Go to latest
Published: May 3, 2020 License: MIT Imports: 64 Imported by: 29

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 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.NewAWSLambda("Hello World",
    helloWorld,
    sparta.IAMRoleDefinition{})

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

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

Visit gosparta.io for complete documentation.

Contributing

Sparta contributions are most welcome. Please consult the latest issues for open issues.

Building

Locally building or testing Sparta itself is typically only needed to make package changes. Sparta is more often used as a required import of another application. Building is done via mage.

To get started building and verifying local changes:

  1. go get -u -d github.com/magefile/mage
  2. In the .../mweagle/Sparta directory, run mage -l to list the current targets:

$ mage -l Targets: build the application clean the working directory compareAgainstMasterBranch is a convenience function to show the comparisons of the current pushed branch against the master branch describe runs the TestDescribe test to generate a describe HTML output file at graph.html docsBuild builds the public documentation site in the /docs folder docsCommit builds and commits the current documentation with an autogenerated comment docsEdit starts a Hugo server and hot reloads the documentation at http://localhost:1313 docsInstallRequirements installs the required Hugo version ensureAllPreconditions ensures that the source passes ALL static ensure* precondition steps ensureCleanTree ensures that the git tree is clean ensureFormatted ensures that the source code is formatted with goimports ensureGoFmt ensures that the source is gofmt -s is empty ensureLint ensures that the source is golinted ensureMarkdownSpelling ensures that all *.MD files are checked for common spelling mistakes ensurePrealloc ensures that slices that could be preallocated are enforced ensureSpelling ensures that there are no misspellings in the source ensureStaticChecks ensures that the source code passes static code checks ensureTravisBuildEnvironment is the command that sets up the Travis environment to run the build. ensureVet ensures that the source has been go vetted generateBuildInfo creates the automatic buildinfo.go file so that we can stamp the SHA into the binaries we build... generateConstants runs the set of commands that update the embedded CONSTANTS for both local and AWS Lambda execution installBuildRequirements installs or updates the dependent packages that aren't referenced by the source, but are needed to build the Sparta source logCodeMetrics ensures that the source code is formatted with goimports publish the latest source test runs the Sparta tests testCover runs the test and opens up the resulting report travisBuild is the task to build in the context of a Travis CI pipeline

Confirm tests are passing on HEAD by first running mage -v test.

As you periodically make local changes, run mage -v test to confirm backward compatibility.

Tests

When possible, please include a test case that verifies the local change and ensures compatibility.

Contributors

Thanks to all Sparta contributors (alphabetical):

Documentation

Index

Examples

Constants

View Source
const (
	// LogFieldRequestID is the fieldname in the context-scoped logger
	// that includes the AWS assigned request ID
	LogFieldRequestID = "reqID"
	// LogFieldARN is the InvokedFunctionArn value
	LogFieldARN = "arn"
	// LogFieldBuildID is the Build ID stamped into the binary exposing
	// the lambda functions
	LogFieldBuildID = "buildID"
	// LogFieldInstanceID is a unique identifier for a given container instance
	LogFieldInstanceID = "instanceID"
)
View Source
const (
	// ScratchDirectory is the cwd relative path component
	// where intermediate build artifacts are created
	ScratchDirectory = ".sparta"
	// EnvVarCustomResourceTypeName is the environment variable
	// name that stores the CustomResource TypeName that should be
	// instantiated
	EnvVarCustomResourceTypeName = "SPARTA_CUSTOM_RESOURCE_TYPE"
)
View Source
const (
	// SpartaVersion defines the current Sparta release
	SpartaVersion = "1.15.0"
	// GoLambdaVersion is the Go version runtime used for the lambda function
	GoLambdaVersion = "go1.x"
	// LambdaBinaryTag is the build tag name used when building the binary
	LambdaBinaryTag = "lambdabinary"
)
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"
	// @enum AWSPrincipal
	ElasticLoadBalancingPrincipal = "elasticloadbalancing.amazonaws.com"
	// @enum KinesisFirehosePrincipal
	KinesisFirehosePrincipal = "firehose.amazonaws.com"
	// @enum EventBridgePrincipal
	EventBridgePrincipal = "events.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 (
	// 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
	// ContextKeyLambdaError is the possible error that was returned
	// from the lambda function
	ContextKeyLambdaError
	// ContextKeyLambdaResponse is the possible response that
	// was returned from the lambda function
	ContextKeyLambdaResponse
	// ContextKeyAWSSession is the aws Session instance for this
	// request
	ContextKeyAWSSession
)
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 (
	// ProperName is the DRY name definition
	ProperName = "Sparta"
)
View Source
const SpartaGitHash = "0bb47c122923388ad10bd9d9f4eaf2938a530ac6"

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
	Status    *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(":*")),
		},
		{
			Effect: "Allow",
			Action: []string{"cloudformation:DescribeStacks",
				"cloudformation:DescribeStackResource"},
			Resource: gocf.Join("", cloudFormationThisStackArn...),
		},

		{
			Effect: "Allow",
			Action: []string{"xray:PutTraceSegments",
				"xray:PutTelemetryRecords",
				"cloudwatch:PutMetricData"},
			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 (
	// SpartaBinaryName is binary name that exposes the Go lambda function
	SpartaBinaryName = fmt.Sprintf("%s.lambda.amd64", ProperName)
)
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 ensures that the provided serviceName is deleted. Failing to delete a non-existent service is considered a success.

func Describe

func Describe(serviceName string,
	serviceDescription string,
	lambdaAWSInfos []*LambdaAWSInfo,
	api APIGateway,
	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 EnsureCustomResourceHandler added in v1.4.0

func EnsureCustomResourceHandler(serviceName string,
	customResourceCloudFormationTypeName string,
	sourceArn *gocf.StringExpr,
	dependsOn []string,
	template *gocf.Template,
	S3Bucket string,
	S3Key string,
	logger *logrus.Logger) (string, error)

EnsureCustomResourceHandler handles ensuring that the custom resource responsible for supporting the operation is actually part of this stack. The returned string value is the CloudFormation resource name that implements this resource. The customResourceCloudFormationTypeName must have already been registered with gocf and implement the resources.CustomResourceCommand interface

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 APIGateway,
	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 ExploreWithInputFilter added in v1.15.0

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

ExploreWithInputFilter allows the caller to provide additional filters for the source files that will be used as inputs

func InstanceID added in v1.5.0

func InstanceID() string

InstanceID returns the uniquely assigned instanceID for this lambda container

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 APIGateway, 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, _ := ctx.Value(ContextKeyLogger).(*logrus.Logger)
	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, _ := NewAWSLambda(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"
	gocf "github.com/mweagle/go-cloudformation"
	"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, _ := ctx.Value(ContextKeyLogger).(*logrus.Logger)
	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)
	// Enable CORS
	apiGateway.CORSOptions = &CORSOptions{
		Headers: map[string]interface{}{
			"Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key",
			"Access-Control-Allow-Methods": "*",
			"Access-Control-Allow-Origin":  gocf.String("*"),
		},
	}
	// Create a lambda function
	echoAPIGatewayLambdaFn, _ := NewAWSLambda(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, _ := NewAWSLambda("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, _ := NewAWSLambda(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 APIGateway,
	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 parses the command line options

Example
package main

import (
	"fmt"
	"os"

	"github.com/pkg/errors"
	"github.com/spf13/cobra"
	validator "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 APIGateway,
	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

func Status added in v1.4.0

func Status(serviceName string,
	serviceDescription string,
	redact bool,
	logger *logrus.Logger) error

Status produces a status report for the given stack

Types

type API

type API struct {

	// Existing API to CloneFrom
	CloneFrom string
	// APIDescription is the user defined description
	Description string

	// Should CORS be enabled for this API?
	CORSEnabled bool
	// CORS options - if non-nil, supersedes CORSEnabled
	CORSOptions *CORSOptions
	// Endpoint configuration information
	EndpointConfiguration *gocf.APIGatewayRestAPIEndpointConfiguration
	// 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) Describe added in v1.9.4

func (api *API) Describe(targetNodeName string) (*DescriptionInfo, error)

Describe returns the API for description

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) Marshal added in v1.9.4

func (api *API) Marshal(serviceName string,
	session *session.Session,
	S3Bucket string,
	S3Key string,
	S3Version string,
	roleNameMap map[string]*gocf.StringExpr,
	template *gocf.Template,
	noop bool,
	logger *logrus.Logger) error

Marshal marshals the API data to a CloudFormation compatible representation

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

func (*API) RestAPIURL added in v1.6.0

func (api *API) RestAPIURL() *gocf.StringExpr

RestAPIURL returns the dynamically assigned Rest API URL including the scheme

type APIGateway added in v1.9.4

type APIGateway interface {
	LogicalResourceName() string
	Marshal(serviceName string,
		session *session.Session,
		S3Bucket string,
		S3Key string,
		S3Version string,
		roleNameMap map[string]*gocf.StringExpr,
		template *gocf.Template,
		noop bool,
		logger *logrus.Logger) error
	Describe(targetNodeName string) (*DescriptionInfo, error)
}

APIGateway repreents a type of API Gateway provisoining that can be exported

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 APIV2 added in v1.9.4

type APIV2 struct {
	APIKeySelectionExpression string
	Description               string
	DisableSchemaValidation   bool
	Tags                      map[string]interface{}
	Version                   string
	// contains filtered or unexported fields
}

APIV2 contains the information necessary for the routes in here. Please tell me they can use the same routes... They cannot

func NewAPIV2 added in v1.9.4

func NewAPIV2(protocol APIV2Protocol,
	name string,
	routeSelectionExpression string,
	stage *APIV2Stage) (*APIV2, error)

NewAPIV2 returns a new API V2 Gateway instance

func (*APIV2) Describe added in v1.9.4

func (apiv2 *APIV2) Describe(targetNodeName string) (*DescriptionInfo, error)

Describe satisfies the API interface

func (*APIV2) LogicalResourceName added in v1.9.4

func (apiv2 *APIV2) LogicalResourceName() string

LogicalResourceName returns the logical resoource name of this API V2 Gateway instance

func (*APIV2) Marshal added in v1.9.4

func (apiv2 *APIV2) Marshal(serviceName string,
	session *session.Session,
	S3Bucket string,
	S3Key string,
	S3Version string,
	roleNameMap map[string]*gocf.StringExpr,
	template *gocf.Template,
	noop bool,
	logger *logrus.Logger) error

Marshal marshals the API V2 Gateway instance to the given template instance

func (*APIV2) NewAPIV2Route added in v1.9.4

func (apiv2 *APIV2) NewAPIV2Route(routeKey APIV2RouteSelectionExpression,
	lambdaFn *LambdaAWSInfo) (*APIV2Route, error)

NewAPIV2Route returns a new Route

func (*APIV2) NewConnectionTableDecorator added in v1.9.4

func (apiv2 *APIV2) NewConnectionTableDecorator(envTableNameKey string,
	propertyName string,
	readCapacity int64,
	writeCapacity int64) (*APIV2GatewayDecorator, error)

NewConnectionTableDecorator returns a *APIV2GatewayDecorator that handles creating the DynamoDDB table and hooking up all the lambda permissions

type APIV2GatewayDecorator added in v1.9.4

type APIV2GatewayDecorator struct {
	// contains filtered or unexported fields
}

APIV2GatewayDecorator is the compound decorator that handles both the DDB table creation and the lambda decorator...winning.

func (*APIV2GatewayDecorator) AnnotateLambdas added in v1.9.4

func (apigd *APIV2GatewayDecorator) AnnotateLambdas(lambdaFns []*LambdaAWSInfo) error

AnnotateLambdas handles hooking up the lambda perms

func (*APIV2GatewayDecorator) DecorateService added in v1.9.4

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

DecorateService handles inserting the DDB Table

type APIV2Integration added in v1.9.4

type APIV2Integration struct {
	//ApiID                       string
	ConnectionType          string
	ContentHandlingStrategy string
	CredentialsArn          gocf.Stringable
	Description             string
	IntegrationMethod       string
	IntegrationType         string
	//IntegrationUri              string
	PassthroughBehavior         string
	RequestParameters           interface{}
	RequestTemplates            interface{}
	TemplateSelectionExpression string
	TimeoutInMillis             int64
}

APIV2Integration is the integration type for an APIV2Route entry

type APIV2Protocol added in v1.9.4

type APIV2Protocol string

APIV2Protocol is the type of API V2 protocols

const (
	// Websocket represents the only supported V2 protocol
	Websocket APIV2Protocol = "WEBSOCKET"
)

type APIV2Route added in v1.9.4

type APIV2Route struct {
	APIKeyRequired                   bool
	AuthorizationScopes              []string
	AuthorizationType                string
	AuthorizerID                     gocf.Stringable
	ModelSelectionExpression         string
	OperationName                    string
	RequestModels                    interface{}
	RequestParameters                interface{}
	RouteResponseSelectionExpression string
	Integration                      *APIV2Integration
	// contains filtered or unexported fields
}

APIV2Route represents a V2 route

type APIV2RouteSelectionExpression added in v1.9.4

type APIV2RouteSelectionExpression string

APIV2RouteSelectionExpression represents a route selection

type APIV2Stage added in v1.9.4

type APIV2Stage struct {
	AccessLogSettings    *gocf.APIGatewayV2StageAccessLogSettings
	ClientCertificateID  gocf.Stringable
	DefaultRouteSettings *gocf.APIGatewayV2StageRouteSettings
	Description          string
	RouteSettings        interface{}

	StageVariables interface{}
	Tags           interface{}
	// contains filtered or unexported fields
}

APIV2Stage represents the deployment stage

func NewAPIV2Stage added in v1.9.4

func NewAPIV2Stage(stageName string) (*APIV2Stage, error)

NewAPIV2Stage returns a new APIV2Stage entry

type AWSLambdaProvider added in v1.15.0

type AWSLambdaProvider interface {
	Handler() interface{}
	Name() string
	Role() interface{}
}

AWSLambdaProvider is an interface that represents a struct that encapsulates a Lambda function

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, _ := NewAWSLambda(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, _ := NewAWSLambda(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 CodeCommitPermission added in v1.9.1

type CodeCommitPermission struct {
	BasePermission
	// RepositoryName
	RepositoryName *gocf.StringExpr
	// Branches to register for
	Branches []string `json:"branches,omitempty"`
	// Events to subscribe to. Defaults to "all" if empty.
	Events []string `json:"events,omitempty"`
}

CodeCommitPermission struct encapsulates the data necessary to trigger the owning LambdaFunction in response to CodeCommit events

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 Describable added in v1.15.0

type Describable interface {
	Describe(targetNodeName string) (*DescriptionInfo, error)
}

Describable represents the interface for something that can provide a description

type DescriptionDisplayInfo added in v1.15.0

type DescriptionDisplayInfo struct {
	SourceNodeColor string
	SourceIcon      *DescriptionIcon
}

DescriptionDisplayInfo encapsulates information that is for display only

type DescriptionIcon added in v1.15.0

type DescriptionIcon struct {
	Category string
	Name     string
}

DescriptionIcon is the struct that contains the category & icon to use when rendering a ndoe

type DescriptionInfo added in v1.15.0

type DescriptionInfo struct {
	Name  string
	Nodes []*DescriptionTriplet
}

DescriptionInfo is the set of information that represents a DescribeableResource

type DescriptionTriplet added in v1.15.0

type DescriptionTriplet struct {
	SourceNodeName string
	ArcLabel       string
	DisplayInfo    *DescriptionDisplayInfo
	TargetNodeName string
}

DescriptionTriplet is a node that should be included in the final describe output.

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 EventBridgePermission added in v1.15.0

type EventBridgePermission struct {
	BasePermission
	// EventBridgeRule for this permission
	Rule *EventBridgeRule
}

EventBridgePermission struct implies that the EventBridge sources should be configured as part of provisioning. The BasePermission.SourceArn isn't considered for this configuration. Each EventBridge Rule or Schedule 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.

type EventBridgeRule added in v1.15.0

type EventBridgeRule struct {
	Description  string
	EventBusName string
	// ArbitraryJSONObject filter for events as documented at
	// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-eventpattern
	// 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
	// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-scheduleexpression
	ScheduleExpression string
}

EventBridgeRule defines parameters for invoking a lambda function in response to specific EventBridge triggers

func (EventBridgeRule) MarshalJSON added in v1.15.0

func (rule EventBridgeRule) MarshalJSON() ([]byte, error)

MarshalJSON customizes the JSON representation used when serializing to the CloudFormation template representation.

type EventSourceMapping

type EventSourceMapping struct {
	StartingPosition               string
	EventSourceArn                 interface{}
	Disabled                       bool
	BatchSize                      int64
	BisectBatchOnFunctionError     bool
	DestinationConfig              *gocf.LambdaEventSourceMappingDestinationConfig
	MaximumBatchingWindowInSeconds int64
	MaximumRecordAgeInSeconds      int64
	MaximumRetryAttempts           int64
	ParallelizationFactor          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{} `json:",omitempty"`
	// Service that requires the action
	Principal interface{} `json:",omitempty"`
	// Optional condition for the privilege
	Condition interface{} `json:",omitempty"`
}

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 Deprecated: Prefer github.com/aws/iam/PolicyStatement instead.

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 Interceptor added in v1.7.0

type Interceptor func(ctx context.Context, msg json.RawMessage) context.Context

Interceptor is the type of an event interceptor that taps the event lifecycle

type InterceptorList added in v1.7.0

type InterceptorList []*NamedInterceptor

InterceptorList is a list of NamedInterceptors

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

	// Lambda Layers
	// Ref: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html#cfn-lambda-function-layers
	Layers []gocf.Stringable

	// interceptors
	Interceptors *LambdaEventInterceptors
	// 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 is deprecated in favor of NewAWSLambda(...)

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, _ := NewAWSLambda(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, _ := NewAWSLambda(LambdaName(lambdaHelloWorld),
		lambdaHelloWorld,
		IAMRoleDefinition{})
	if nil != helloWorldLambda {
		fmt.Printf("Failed to create new Lambda function")
	}
}
Output:

func NewAWSLambda added in v1.6.0

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

NewAWSLambda is the creation function that replaces HandleAWSLambda. It returns a *LambdaAWSInfo pointer to the struct representing the AWS lambda target. It's a go-friendly signature for creating a lambda function

func NewAWSLambdaFromProvider added in v1.15.0

func NewAWSLambdaFromProvider(provider AWSLambdaProvider) (*LambdaAWSInfo, error)

NewAWSLambdaFromProvider is a utility function to return an LambdaAWSInfo from an AWSLambdaProvider

func (*LambdaAWSInfo) Description added in v1.15.0

func (info *LambdaAWSInfo) Description(targetNodeName string) ([]*DescriptionTriplet, error)

Description satisfies the Describable interface

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) NewDescriptionTriplet added in v1.15.0

func (info *LambdaAWSInfo) NewDescriptionTriplet(nodeName string, lambdaIsTarget bool) *DescriptionTriplet

NewDescriptionTriplet returns a decription triplet where this lambda is either a sink or a source

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"
	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, _ := lambdacontext.FromContext(ctx)

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

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

func main() {

	lambdaFn, _ := NewAWSLambda(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 LambdaEventInterceptors added in v1.7.0

type LambdaEventInterceptors struct {
	Begin          InterceptorList
	BeforeSetup    InterceptorList
	AfterSetup     InterceptorList
	BeforeDispatch InterceptorList
	AfterDispatch  InterceptorList
	Complete       InterceptorList
}

LambdaEventInterceptors is the struct that stores event handlers that tap into the normal event dispatching workflow

func (*LambdaEventInterceptors) Register added in v1.7.0

Register is a convenience function to register a struct that implements the LambdaInterceptorProvider interface

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 LambdaInterceptorProvider added in v1.7.0

type LambdaInterceptorProvider interface {
	Begin(ctx context.Context, msg json.RawMessage) context.Context
	BeforeSetup(ctx context.Context, msg json.RawMessage) context.Context
	AfterSetup(ctx context.Context, msg json.RawMessage) context.Context
	BeforeDispatch(ctx context.Context, msg json.RawMessage) context.Context
	AfterDispatch(ctx context.Context, msg json.RawMessage) context.Context
	Complete(ctx context.Context, msg json.RawMessage) context.Context
}

LambdaInterceptorProvider is the interface that defines an event interceptor Interceptors are able to hook into the normal event processing pipeline

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 NamedInterceptor added in v1.7.0

type NamedInterceptor struct {
	Name        string
	Interceptor Interceptor
}

NamedInterceptor represents a named interceptor that's invoked in the event path

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 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, _ := NewAWSLambda(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
	// BucketName is the name of the bucket to create. Required
	// to specify a CloudFront Distribution
	BucketName *gocf.StringExpr
	// UserManifestData is a map of optional data to include
	// in the MANIFEST.json data at the site root. These optional
	// values will be scoped to a `userdata` key in the MANIFEST.json
	// object
	UserManifestData map[string]interface{}
	// 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, _ := NewAWSLambda(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, _ := NewAWSLambda(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, _ := NewAWSLambda(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,
	S3Key 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,
	S3Key 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,
	S3Key string,
	buildID string,
	awsSession *session.Session,
	noop bool,
	logger *logrus.Logger) error

DecorateService calls sdhf(...) to satisfy ServiceDecoratorHookHandler

type ServiceDecoratorHookHandler added in v1.3.0

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

ServiceDecoratorHookHandler is the interface type to indicate a workflow hook

type ServiceValidationHook added in v1.5.0

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

ServiceValidationHook defines a user function that is called a single after all template annotations have been performed. It is where policies should be applied

type ServiceValidationHookFunc added in v1.5.0

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

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

func (ServiceValidationHookFunc) ValidateService added in v1.7.2

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

ValidateService calls sdhf(...) to satisfy ServiceValidationHookHandler

type ServiceValidationHookHandler added in v1.5.0

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

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

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 TemplateHook into a TemplateDecoratorHandler 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

	// Validators are hooks that are called when all marshalling
	// is complete. Each hook receives a complete read-only
	// copy of the materialized template.
	Validators []ServiceValidationHookHandler

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

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

Directories

Path Synopsis
Package archetype provides a set of convenience functions that transform a free function or struct implementing a specific interface into a *sparta.LambdaAWSInfo struct complete with the necessary AWS permissions.
Package archetype provides a set of convenience functions that transform a free function or struct implementing a specific interface into a *sparta.LambdaAWSInfo struct complete with the necessary AWS permissions.
rest
Package rest provides a set of utility functions to make building REST-based services simpler.
Package rest provides a set of utility functions to make building REST-based services simpler.
aws
Package aws scopes functionality and types that bridge Sparta types with native AWS types.
Package aws scopes functionality and types that bridge Sparta types with native AWS types.
apigateway
Package apigateway provides a standard serialization format to wrap API Gateway responses that translate into specific end-user errors.
Package apigateway provides a standard serialization format to wrap API Gateway responses that translate into specific end-user errors.
cloudformation
Package cloudformation scopes CloudFormation-specific utiltities for Sparta
Package cloudformation scopes CloudFormation-specific utiltities for Sparta
cloudformation/cli
Package main provides a simple cli tool to produce a DescribeStackResponse for a given CloudFormation Stack Name or ID.
Package main provides a simple cli tool to produce a DescribeStackResponse for a given CloudFormation Stack Name or ID.
cloudformation/resources
Package resources defines a set of CloudFormation Custom Resources that are implemented by Lambda functions.
Package resources defines a set of CloudFormation Custom Resources that are implemented by Lambda functions.
cloudwatch
Package cloudwatch scopes CloudWatch-specific utiltities for Sparta
Package cloudwatch scopes CloudWatch-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.
events
Package events defines event types that are un/marshalled to and from other AWS services.
Package events defines event types that are un/marshalled to and from other AWS services.
iam
Package iam exposes types and functionality to work with with AWS IAM service
Package iam exposes types and functionality to work with with AWS IAM service
iam/builder
Package iambuilder exposes a fluent IAM privilege builder
Package iambuilder exposes a fluent IAM privilege builder
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.
step
Package step provides functionality to work with AWS Step Functions
Package step provides functionality to work with AWS Step Functions
cmd
Package decorator exposes Sparta decorator types to mutate the CloudFormation template
Package decorator exposes Sparta decorator types to mutate the CloudFormation template
Package docker exposes functionality to manage building and posting Docker containers
Package docker exposes functionality to manage building and posting Docker containers
Package interceptor defines Sparta interceptors that tap the event handling workflow.
Package interceptor defines Sparta interceptors that tap the event handling workflow.
Package system provide system level operations
Package system provide system level operations
Package testing exports helper functions to streamline testing core Sparta codepaths.
Package testing exports helper functions to streamline testing core Sparta codepaths.
Package zip exposes convenience functions to work with ZIP archives
Package zip exposes convenience functions to work with ZIP archives

Jump to

Keyboard shortcuts

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