本文整理汇总了Golang中github.com/crewjam/go-cloudformation.Template类的典型用法代码示例。如果您正苦于以下问题:Golang Template类的具体用法?Golang Template怎么用?Golang Template使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Template类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: templateDecorator
func templateDecorator(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 {
// Add an empty resource
newResource, err := newCloudFormationResource("Custom::ProvisionTestEmpty", logger)
if nil != err {
return err
}
customResource := newResource.(*cloudFormationProvisionTestResource)
customResource.ServiceToken = "arn:aws:sns:us-east-1:84969EXAMPLE:CRTest"
customResource.TestKey = "Hello World"
cfTemplate.AddResource("ProvisionTestResource", customResource)
// Add an output
cfTemplate.Outputs["OutputDecorationTest"] = &gocf.Output{
Description: "Information about the value",
Value: gocf.String("My key"),
}
return nil
}
示例2: export
func (perm SNSPermission) export(serviceName string,
lambdaFunctionDisplayName string,
lambdaLogicalCFResourceName string,
template *gocf.Template,
S3Bucket string,
S3Key string,
logger *logrus.Logger) (string, error) {
sourceArnExpression := perm.BasePermission.sourceArnExpr(snsSourceArnParts...)
targetLambdaResourceName, err := perm.BasePermission.export(gocf.String(SNSPrincipal),
snsSourceArnParts,
lambdaFunctionDisplayName,
lambdaLogicalCFResourceName,
template,
S3Bucket,
S3Key,
logger)
if nil != err {
return "", err
}
// Make sure the custom lambda that manages s3 notifications is provisioned.
configuratorResName, err := ensureCustomResourceHandler(serviceName,
cloudformationresources.SNSLambdaEventSource,
sourceArnExpression,
[]string{},
template,
S3Bucket,
S3Key,
logger)
if nil != err {
return "", err
}
// Add a custom resource invocation for this configuration
//////////////////////////////////////////////////////////////////////////////
newResource, newResourceError := newCloudFormationResource(cloudformationresources.SNSLambdaEventSource, logger)
if nil != newResourceError {
return "", newResourceError
}
customResource := newResource.(*cloudformationresources.SNSLambdaEventSourceResource)
customResource.ServiceToken = gocf.GetAtt(configuratorResName, "Arn")
customResource.LambdaTargetArn = gocf.GetAtt(lambdaLogicalCFResourceName, "Arn")
customResource.SNSTopicArn = sourceArnExpression
// Name?
resourceInvokerName := CloudFormationResourceName("ConfigSNS",
lambdaLogicalCFResourceName,
perm.BasePermission.SourceAccount)
// Add it
cfResource := template.AddResource(resourceInvokerName, customResource)
cfResource.DependsOn = append(cfResource.DependsOn,
targetLambdaResourceName,
configuratorResName)
return "", nil
}
示例3: export
func (resourceInfo *customResourceInfo) export(serviceName string,
targetLambda *gocf.StringExpr,
S3Bucket string,
S3Key string,
roleNameMap map[string]*gocf.StringExpr,
template *gocf.Template,
logger *logrus.Logger) error {
// Figure out the role name
iamRoleArnName := resourceInfo.roleName
// If there is no user supplied role, that means that the associated
// IAMRoleDefinition name has been created and this resource needs to
// depend on that being created.
if iamRoleArnName == "" && resourceInfo.roleDefinition != nil {
iamRoleArnName = resourceInfo.roleDefinition.logicalName(serviceName, resourceInfo.userFunctionName)
}
lambdaDescription := resourceInfo.options.Description
if "" == lambdaDescription {
lambdaDescription = fmt.Sprintf("%s CustomResource: %s", serviceName, resourceInfo.userFunctionName)
}
// Create the Lambda Function
lambdaResource := gocf.LambdaFunction{
Code: &gocf.LambdaFunctionCode{
S3Bucket: gocf.String(S3Bucket),
S3Key: gocf.String(S3Key),
},
Description: gocf.String(lambdaDescription),
Handler: gocf.String(fmt.Sprintf("index.%s", resourceInfo.jsHandlerName())),
MemorySize: gocf.Integer(resourceInfo.options.MemorySize),
Role: roleNameMap[iamRoleArnName],
Runtime: gocf.String(NodeJSVersion),
Timeout: gocf.Integer(resourceInfo.options.Timeout),
VpcConfig: resourceInfo.options.VpcConfig,
}
lambdaFunctionCFName := CloudFormationResourceName("CustomResourceLambda",
resourceInfo.userFunctionName,
resourceInfo.logicalName())
cfResource := template.AddResource(lambdaFunctionCFName, lambdaResource)
safeMetadataInsert(cfResource, "golangFunc", resourceInfo.userFunctionName)
// And create the CustomResource that actually invokes it...
newResource, newResourceError := newCloudFormationResource(cloudFormationLambda, logger)
if nil != newResourceError {
return newResourceError
}
customResource := newResource.(*cloudFormationLambdaCustomResource)
customResource.ServiceToken = gocf.GetAtt(lambdaFunctionCFName, "Arn")
customResource.UserProperties = resourceInfo.properties
template.AddResource(resourceInfo.logicalName(), customResource)
return nil
}
示例4: export
func (perm BasePermission) export(principal string,
arnPrefixParts []gocf.Stringable,
lambdaLogicalCFResourceName string,
template *gocf.Template,
S3Bucket string,
S3Key string,
logger *logrus.Logger) (string, error) {
lambdaPermission := gocf.LambdaPermission{
Action: gocf.String("lambda:InvokeFunction"),
FunctionName: gocf.GetAtt(lambdaLogicalCFResourceName, "Arn"),
Principal: gocf.String(principal),
}
// If the Arn isn't the wildcard value, then include it.
if nil != perm.SourceArn {
switch perm.SourceArn.(type) {
case string:
// Don't be smart if the Arn value is a user supplied literal
if "*" != perm.SourceArn.(string) {
lambdaPermission.SourceArn = gocf.String(perm.SourceArn.(string))
}
default:
lambdaPermission.SourceArn = perm.sourceArnExpr(arnPrefixParts...)
}
}
if "" != perm.SourceAccount {
lambdaPermission.SourceAccount = gocf.String(perm.SourceAccount)
}
hash := sha1.New()
hash.Write([]byte(fmt.Sprintf("%v", lambdaPermission)))
resourceName := fmt.Sprintf("LambdaPerm%s", hex.EncodeToString(hash.Sum(nil)))
template.AddResource(resourceName, lambdaPermission)
return resourceName, nil
}
示例5: ensureCustomResourceHandler
func ensureCustomResourceHandler(serviceName string,
customResourceTypeName string,
sourceArn *gocf.StringExpr,
dependsOn []string,
template *gocf.Template,
S3Bucket string,
S3Key string,
logger *logrus.Logger) (string, error) {
// AWS service basename
awsServiceName := awsPrincipalToService(customResourceTypeName)
// Use a stable resource CloudFormation resource name to represent
// the single CustomResource that can configure the different
// PushSource's for the given principal.
keyName, err := json.Marshal(ArbitraryJSONObject{
"Principal": customResourceTypeName,
"ServiceName": awsServiceName,
})
if err != nil {
logger.Error("Failed to create configurator resource name: ", err.Error())
return "", err
}
subscriberHandlerName := CloudFormationResourceName(fmt.Sprintf("%sCustomResource", awsServiceName),
string(keyName))
//////////////////////////////////////////////////////////////////////////////
// IAM Role definition
iamResourceName, err := ensureIAMRoleForCustomResource(customResourceTypeName, sourceArn, template, logger)
if nil != err {
return "", err
}
iamRoleRef := gocf.GetAtt(iamResourceName, "Arn")
_, exists := template.Resources[subscriberHandlerName]
if !exists {
logger.WithFields(logrus.Fields{
"Service": customResourceTypeName,
}).Debug("Including Lambda CustomResource for AWS Service")
configuratorDescription := customResourceDescription(serviceName, customResourceTypeName)
//////////////////////////////////////////////////////////////////////////////
// Custom Resource Lambda Handler
// The export name MUST correspond to the createForwarder entry that is dynamically
// written into the index.js file during compile in createNewSpartaCustomResourceEntry
handlerName := lambdaExportNameForCustomResourceType(customResourceTypeName)
logger.WithFields(logrus.Fields{
"CustomResourceType": customResourceTypeName,
"NodeJSExport": handlerName,
}).Debug("Sparta CloudFormation custom resource handler info")
customResourceHandlerDef := gocf.LambdaFunction{
Code: &gocf.LambdaFunctionCode{
S3Bucket: gocf.String(S3Bucket),
S3Key: gocf.String(S3Key),
},
Description: gocf.String(configuratorDescription),
Handler: gocf.String(handlerName),
Role: iamRoleRef,
Runtime: gocf.String(NodeJSVersion),
Timeout: gocf.Integer(30),
}
cfResource := template.AddResource(subscriberHandlerName, customResourceHandlerDef)
if nil != dependsOn && (len(dependsOn) > 0) {
cfResource.DependsOn = append(cfResource.DependsOn, dependsOn...)
}
}
return subscriberHandlerName, nil
}
示例6: ensureIAMRoleForCustomResource
// ensureIAMRoleForCustomResource ensures that the single IAM::Role for a single
// AWS principal (eg, s3.*.*) exists, and includes statements for the given
// sourceArn. Sparta uses a single IAM::Role for the CustomResource configuration
// lambda, which is the union of all Arns in the application.
func ensureIAMRoleForCustomResource(awsPrincipalName string,
sourceArn *gocf.StringExpr,
template *gocf.Template,
logger *logrus.Logger) (string, error) {
var principalActions []string
switch awsPrincipalName {
case cloudformationresources.SNSLambdaEventSource:
principalActions = PushSourceConfigurationActions.SNSLambdaEventSource
case cloudformationresources.S3LambdaEventSource:
principalActions = PushSourceConfigurationActions.S3LambdaEventSource
case cloudformationresources.SESLambdaEventSource:
principalActions = PushSourceConfigurationActions.SESLambdaEventSource
case cloudformationresources.CloudWatchLogsLambdaEventSource:
principalActions = PushSourceConfigurationActions.CloudWatchLogsLambdaEventSource
default:
return "", fmt.Errorf("Unsupported principal for IAM role creation: %s", awsPrincipalName)
}
// What's the stable IAMRoleName?
resourceBaseName := fmt.Sprintf("CustomResource%sIAMRole", awsPrincipalToService(awsPrincipalName))
stableRoleName := CloudFormationResourceName(resourceBaseName, awsPrincipalName)
// Ensure it exists, then check to see if this Source ARN is already specified...
// Checking equality with Stringable?
// Create a new Role
var existingIAMRole *gocf.IAMRole
existingResource, exists := template.Resources[stableRoleName]
logger.WithFields(logrus.Fields{
"PrincipalActions": principalActions,
"SourceArn": sourceArn,
}).Debug("Ensuring IAM Role results")
if !exists {
// Insert the IAM role here. We'll walk the policies data in the next section
// to make sure that the sourceARN we have is in the list
statements := CommonIAMStatements.Core
iamPolicyList := gocf.IAMPoliciesList{}
iamPolicyList = append(iamPolicyList,
gocf.IAMPolicies{
PolicyDocument: ArbitraryJSONObject{
"Version": "2012-10-17",
"Statement": statements,
},
PolicyName: gocf.String(fmt.Sprintf("%sPolicy", stableRoleName)),
},
)
existingIAMRole = &gocf.IAMRole{
AssumeRolePolicyDocument: AssumePolicyDocument,
Policies: &iamPolicyList,
}
template.AddResource(stableRoleName, existingIAMRole)
// Create a new IAM Role resource
logger.WithFields(logrus.Fields{
"RoleName": stableRoleName,
}).Debug("Inserting IAM Role")
} else {
existingIAMRole = existingResource.Properties.(*gocf.IAMRole)
}
// Walk the existing statements
if nil != existingIAMRole.Policies {
for _, eachPolicy := range *existingIAMRole.Policies {
policyDoc := eachPolicy.PolicyDocument.(ArbitraryJSONObject)
statements := policyDoc["Statement"]
for _, eachStatement := range statements.([]spartaIAM.PolicyStatement) {
if sourceArn.String() == eachStatement.Resource.String() {
logger.WithFields(logrus.Fields{
"RoleName": stableRoleName,
"SourceArn": sourceArn.String(),
}).Debug("SourceArn already exists for IAM Policy")
return stableRoleName, nil
}
}
}
logger.WithFields(logrus.Fields{
"RoleName": stableRoleName,
"Action": principalActions,
"Resource": sourceArn,
}).Debug("Inserting Actions for configuration ARN")
// Add this statement to the first policy, iff the actions are non-empty
if len(principalActions) > 0 {
rootPolicy := (*existingIAMRole.Policies)[0]
rootPolicyDoc := rootPolicy.PolicyDocument.(ArbitraryJSONObject)
rootPolicyStatements := rootPolicyDoc["Statement"].([]spartaIAM.PolicyStatement)
rootPolicyDoc["Statement"] = append(rootPolicyStatements, spartaIAM.PolicyStatement{
Effect: "Allow",
Action: principalActions,
Resource: sourceArn,
})
//.........这里部分代码省略.........
示例7: AddAutoIncrementingLambdaVersionResource
// AddAutoIncrementingLambdaVersionResource inserts a new
// AWS::Lambda::Version resource into the template. It uses
// the existing CloudFormation template representation
// to determine the version index to append. The returned
// map is from `versionIndex`->`CloudFormationResourceName`
// to support second-order AWS::Lambda::Alias records on a
// per-version level
func AddAutoIncrementingLambdaVersionResource(serviceName string,
lambdaResourceName string,
cfTemplate *gocf.Template,
logger *logrus.Logger) (*AutoIncrementingLambdaVersionInfo, error) {
// Get the template
session, sessionErr := session.NewSession()
if sessionErr != nil {
return nil, sessionErr
}
// Get the current template - for each version we find in the version listing
// we look up the actual CF resource and copy it into this template
existingStackDefinition, existingStackDefinitionErr := existingStackTemplate(serviceName,
session,
logger)
if nil != existingStackDefinitionErr {
return nil, existingStackDefinitionErr
}
existingVersions, existingVersionsErr := existingLambdaResourceVersions(serviceName,
lambdaResourceName,
session,
logger)
if nil != existingVersionsErr {
return nil, existingVersionsErr
}
// Initialize the auto incrementing version struct
autoIncrementingLambdaVersionInfo := AutoIncrementingLambdaVersionInfo{
CurrentVersion: 0,
CurrentVersionResourceName: "",
VersionHistory: make(map[int]string, 0),
}
lambdaVersionResourceName := func(versionIndex int) string {
return CloudFormationResourceName(lambdaResourceName,
"version",
strconv.Itoa(versionIndex))
}
if nil != existingVersions {
// Add the CloudFormation resource
logger.WithFields(logrus.Fields{
"VersionCount": len(existingVersions.Versions) - 1, // Ignore $LATEST
"ResourceName": lambdaResourceName,
}).Info("Total number of published versions")
for _, eachEntry := range existingVersions.Versions {
versionIndex, versionIndexErr := strconv.Atoi(*eachEntry.Version)
if nil == versionIndexErr {
// Find the existing resource...
versionResourceName := lambdaVersionResourceName(versionIndex)
if nil == existingStackDefinition {
return nil, fmt.Errorf("Unable to find exising Version resource in nil Template")
}
cfResourceDefinition, cfResourceDefinitionExists := existingStackDefinition.Resources[versionResourceName]
if !cfResourceDefinitionExists {
return nil, fmt.Errorf("Unable to find exising Version resource (Resource: %s, Version: %d) in template",
versionResourceName,
versionIndex)
}
cfTemplate.Resources[versionResourceName] = cfResourceDefinition
// Add the CloudFormation resource
logger.WithFields(logrus.Fields{
"Version": versionIndex,
"ResourceName": versionResourceName,
}).Debug("Preserving Lambda version")
// Store the state, tracking the latest version
autoIncrementingLambdaVersionInfo.VersionHistory[versionIndex] = versionResourceName
if versionIndex > autoIncrementingLambdaVersionInfo.CurrentVersion {
autoIncrementingLambdaVersionInfo.CurrentVersion = versionIndex
}
}
}
}
// Bump the version and add a new entry...
autoIncrementingLambdaVersionInfo.CurrentVersion++
versionResource := &gocf.LambdaVersion{
FunctionName: gocf.GetAtt(lambdaResourceName, "Arn").String(),
}
autoIncrementingLambdaVersionInfo.CurrentVersionResourceName = lambdaVersionResourceName(autoIncrementingLambdaVersionInfo.CurrentVersion)
cfTemplate.AddResource(autoIncrementingLambdaVersionInfo.CurrentVersionResourceName, versionResource)
// Log the version we're about to publish...
logger.WithFields(logrus.Fields{
"ResourceName": lambdaResourceName,
"StackVersion": autoIncrementingLambdaVersionInfo.CurrentVersion,
}).Info("Inserting new version resource")
return &autoIncrementingLambdaVersionInfo, nil
//.........这里部分代码省略.........
示例8: export
// export marshals the API data to a CloudFormation compatible representation
func (api *API) export(S3Bucket string,
S3Key string,
roleNameMap map[string]*gocf.StringExpr,
template *gocf.Template,
logger *logrus.Logger) error {
lambdaResourceName, err := ensureConfiguratorLambdaResource(APIGatewayPrincipal,
gocf.String("*"),
[]string{},
template,
S3Bucket,
S3Key,
logger)
if nil != err {
return err
}
// If this API is CORS enabled, then annotate the APIResources with OPTION
// entries. Slight overhead in network I/O due to marshalling data, but simplifies
// the CustomResource, which is only a temporary stopgap until cloudformation
// properly supports APIGateway
responseParameters := map[string]bool{
"method.response.header.Access-Control-Allow-Headers": true,
"method.response.header.Access-Control-Allow-Methods": true,
"method.response.header.Access-Control-Allow-Origin": true,
}
integrationResponseParameters := map[string]string{
"method.response.header.Access-Control-Allow-Headers": "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'",
"method.response.header.Access-Control-Allow-Methods": "'*'",
"method.response.header.Access-Control-Allow-Origin": "'*'",
}
// Keep track of how many resources && methods we're supposed to provision. If there
// aren't any, then throw an error
resourceCount := 0
methodCount := 0
// We need to update the default values here, because the individual
// methods are deserialized they annotate the prexisting responses with whitelist data.
for _, eachResource := range api.resources {
resourceCount++
if api.CORSEnabled {
// Create the OPTIONS entry
method, err := eachResource.NewMethod("OPTIONS")
if err != nil {
return err
}
methodCount++
statusOkResponse := defaultResponse()
statusOkResponse.Parameters = responseParameters
method.Responses[200] = statusOkResponse
method.Integration = Integration{
Parameters: make(map[string]string, 0),
RequestTemplates: make(map[string]string, 0),
Responses: make(map[int]*IntegrationResponse, 0),
integrationType: "MOCK",
}
method.Integration.RequestTemplates["application/json"] = "{\"statusCode\": 200}"
corsIntegrationResponse := IntegrationResponse{
Parameters: integrationResponseParameters,
Templates: map[string]string{
"application/json": "",
},
}
method.Integration.Responses[200] = &corsIntegrationResponse
}
for _, eachMethod := range eachResource.Methods {
methodCount++
statusSuccessfulCode := http.StatusOK
if eachMethod.httpMethod == "POST" {
statusSuccessfulCode = http.StatusCreated
}
if len(eachMethod.Responses) <= 0 {
eachMethod.Responses = DefaultMethodResponses(statusSuccessfulCode)
}
if api.CORSEnabled {
for _, eachResponse := range eachMethod.Responses {
if nil == eachResponse.Parameters {
eachResponse.Parameters = make(map[string]bool, 0)
}
for eachKey, eachBool := range responseParameters {
eachResponse.Parameters[eachKey] = eachBool
}
}
}
// Update Integration
if len(eachMethod.Integration.Responses) <= 0 {
eachMethod.Integration.Responses = DefaultIntegrationResponses(statusSuccessfulCode)
}
if api.CORSEnabled {
for eachHTTPStatus, eachIntegrationResponse := range eachMethod.Integration.Responses {
if eachHTTPStatus >= 200 && eachHTTPStatus <= 299 {
if nil == eachIntegrationResponse.Parameters {
eachIntegrationResponse.Parameters = make(map[string]string, 0)
}
for eachKey, eachValue := range integrationResponseParameters {
//.........这里部分代码省略.........
示例9: export
// export marshals the API data to a CloudFormation compatible representation
func (api *API) export(serviceName string,
session *session.Session,
S3Bucket string,
S3Key string,
roleNameMap map[string]*gocf.StringExpr,
template *gocf.Template,
noop bool,
logger *logrus.Logger) error {
apiGatewayResourceNameForPath := func(fullPath string) string {
pathParts := strings.Split(fullPath, "/")
return CloudFormationResourceName("%sResource", pathParts[0], fullPath)
}
apiGatewayResName := CloudFormationResourceName("APIGateway", api.name)
// Create an API gateway entry
apiGatewayRes := &gocf.ApiGatewayRestApi{
Description: gocf.String(api.Description),
FailOnWarnings: gocf.Bool(false),
Name: gocf.String(api.name),
}
if "" != api.CloneFrom {
apiGatewayRes.CloneFrom = gocf.String(api.CloneFrom)
}
if "" == api.Description {
apiGatewayRes.Description = gocf.String(fmt.Sprintf("%s RestApi", serviceName))
} else {
apiGatewayRes.Description = gocf.String(api.Description)
}
template.AddResource(apiGatewayResName, apiGatewayRes)
apiGatewayRestAPIID := gocf.Ref(apiGatewayResName)
// List of all the method resources we're creating s.t. the
// deployment can DependOn them
optionsMethodPathMap := make(map[string]bool)
var apiMethodCloudFormationResources []string
for eachResourceMethodKey, eachResourceDef := range api.resources {
// First walk all the user resources and create intermediate paths
// to repreesent all the resources
var parentResource *gocf.StringExpr
pathParts := strings.Split(strings.TrimLeft(eachResourceDef.pathPart, "/"), "/")
pathAccumulator := []string{"/"}
for index, eachPathPart := range pathParts {
pathAccumulator = append(pathAccumulator, eachPathPart)
resourcePathName := apiGatewayResourceNameForPath(strings.Join(pathAccumulator, "/"))
if _, exists := template.Resources[resourcePathName]; !exists {
cfResource := &gocf.ApiGatewayResource{
RestApiId: apiGatewayRestAPIID.String(),
PathPart: gocf.String(eachPathPart),
}
if index <= 0 {
cfResource.ParentId = gocf.GetAtt(apiGatewayResName, "RootResourceId")
} else {
cfResource.ParentId = parentResource
}
template.AddResource(resourcePathName, cfResource)
}
parentResource = gocf.Ref(resourcePathName).String()
}
// Add the lambda permission
apiGatewayPermissionResourceName := CloudFormationResourceName("APIGatewayLambdaPerm", eachResourceMethodKey)
lambdaInvokePermission := &gocf.LambdaPermission{
Action: gocf.String("lambda:InvokeFunction"),
FunctionName: gocf.GetAtt(eachResourceDef.parentLambda.logicalName(), "Arn"),
Principal: gocf.String(APIGatewayPrincipal),
}
template.AddResource(apiGatewayPermissionResourceName, lambdaInvokePermission)
// BEGIN CORS - OPTIONS verb
// CORS is API global, but it's possible that there are multiple different lambda functions
// that are handling the same HTTP resource. In this case, track whether we've already created an
// OPTIONS entry for this path and only append iff this is the first time through
if api.CORSEnabled {
methodResourceName := CloudFormationResourceName(fmt.Sprintf("%s-OPTIONS", eachResourceDef.pathPart), eachResourceDef.pathPart)
_, resourceExists := optionsMethodPathMap[methodResourceName]
if !resourceExists {
template.AddResource(methodResourceName, corsOptionsGatewayMethod(apiGatewayRestAPIID, parentResource))
apiMethodCloudFormationResources = append(apiMethodCloudFormationResources, methodResourceName)
optionsMethodPathMap[methodResourceName] = true
}
}
// END CORS - OPTIONS verb
// BEGIN - user defined verbs
for eachMethodName, eachMethodDef := range eachResourceDef.Methods {
apiGatewayMethod := &gocf.ApiGatewayMethod{
HttpMethod: gocf.String(eachMethodName),
AuthorizationType: gocf.String("NONE"),
ResourceId: parentResource.String(),
RestApiId: apiGatewayRestAPIID.String(),
Integration: &gocf.APIGatewayMethodIntegration{
IntegrationHttpMethod: gocf.String("POST"),
Type: gocf.String("AWS"),
RequestTemplates: defaultRequestTemplates(),
Uri: gocf.Join("",
gocf.String("arn:aws:apigateway:"),
//.........这里部分代码省略.........
示例10: export
// Marshal this object into 1 or more CloudFormation resource definitions that are accumulated
// in the resources map
func (info *LambdaAWSInfo) export(serviceName string,
S3Bucket string,
S3Key string,
roleNameMap map[string]*gocf.StringExpr,
template *gocf.Template,
logger *logrus.Logger) error {
// If we have RoleName, then get the ARN, otherwise get the Ref
var dependsOn []string
if nil != info.DependsOn {
dependsOn = append(dependsOn, info.DependsOn...)
}
iamRoleArnName := info.RoleName
// If there is no user supplied role, that means that the associated
// IAMRoleDefinition name has been created and this resource needs to
// depend on that being created.
if iamRoleArnName == "" && info.RoleDefinition != nil {
iamRoleArnName = info.RoleDefinition.logicalName()
dependsOn = append(dependsOn, info.RoleDefinition.logicalName())
}
lambdaDescription := info.Options.Description
if "" == lambdaDescription {
lambdaDescription = fmt.Sprintf("%s: %s", serviceName, info.lambdaFnName)
}
// Create the primary resource
lambdaResource := gocf.LambdaFunction{
Code: &gocf.LambdaFunctionCode{
S3Bucket: gocf.String(S3Bucket),
S3Key: gocf.String(S3Key),
},
Description: gocf.String(lambdaDescription),
Handler: gocf.String(fmt.Sprintf("index.%s", info.jsHandlerName())),
MemorySize: gocf.Integer(info.Options.MemorySize),
Role: roleNameMap[iamRoleArnName],
Runtime: gocf.String("nodejs"),
Timeout: gocf.Integer(info.Options.Timeout),
}
cfResource := template.AddResource(info.logicalName(), lambdaResource)
cfResource.DependsOn = append(cfResource.DependsOn, dependsOn...)
safeMetadataInsert(cfResource, "golangFunc", info.lambdaFnName)
// Create the lambda Ref in case we need a permission or event mapping
functionAttr := gocf.GetAtt(info.logicalName(), "Arn")
// Permissions
for _, eachPermission := range info.Permissions {
_, err := eachPermission.export(serviceName,
info.logicalName(),
template,
S3Bucket,
S3Key,
logger)
if nil != err {
return err
}
}
// Event Source Mappings
hash := sha1.New()
for _, eachEventSourceMapping := range info.EventSourceMappings {
eventSourceMappingResource := gocf.LambdaEventSourceMapping{
EventSourceArn: gocf.String(eachEventSourceMapping.EventSourceArn),
FunctionName: functionAttr,
StartingPosition: gocf.String(eachEventSourceMapping.StartingPosition),
BatchSize: gocf.Integer(eachEventSourceMapping.BatchSize),
Enabled: gocf.Bool(!eachEventSourceMapping.Disabled),
}
hash.Write([]byte(eachEventSourceMapping.EventSourceArn))
binary.Write(hash, binary.LittleEndian, eachEventSourceMapping.BatchSize)
hash.Write([]byte(eachEventSourceMapping.StartingPosition))
resourceName := fmt.Sprintf("LambdaES%s", hex.EncodeToString(hash.Sum(nil)))
template.AddResource(resourceName, eventSourceMappingResource)
}
// Decorator
if nil != info.Decorator {
logger.Debug("Decorator found for Lambda: ", info.lambdaFnName)
// Create an empty template so that we can track whether things
// are overwritten
decoratorProxyTemplate := gocf.NewTemplate()
err := info.Decorator(info.logicalName(),
lambdaResource,
decoratorProxyTemplate,
logger)
if nil != err {
return err
}
// Append the custom resources
err = safeMergeTemplates(decoratorProxyTemplate, template, logger)
if nil != err {
return fmt.Errorf("Lambda (%s) decorator created conflicting resources", info.lambdaFnName)
}
}
return nil
//.........这里部分代码省略.........
示例11: export
// export marshals the API data to a CloudFormation compatible representation
func (s3Site *S3Site) export(S3Bucket string,
S3Key string,
S3ResourcesKey string,
apiGatewayOutputs map[string]*gocf.Output,
roleNameMap map[string]*gocf.StringExpr,
template *gocf.Template,
logger *logrus.Logger) error {
websiteConfig := s3Site.WebsiteConfiguration
if nil == websiteConfig {
websiteConfig = &s3.WebsiteConfiguration{}
}
//////////////////////////////////////////////////////////////////////////////
// 1 - Create the S3 bucket. The "BucketName" property is empty s.t.
// AWS will assign a unique one.
if nil == websiteConfig.ErrorDocument {
websiteConfig.ErrorDocument = &s3.ErrorDocument{
Key: aws.String("error.html"),
}
}
if nil == websiteConfig.IndexDocument {
websiteConfig.IndexDocument = &s3.IndexDocument{
Suffix: aws.String("index.html"),
}
}
s3WebsiteConfig := &gocf.S3WebsiteConfigurationProperty{
ErrorDocument: gocf.String(aws.StringValue(websiteConfig.ErrorDocument.Key)),
IndexDocument: gocf.String(aws.StringValue(websiteConfig.IndexDocument.Suffix)),
}
s3Bucket := &gocf.S3Bucket{
AccessControl: gocf.String("PublicRead"),
WebsiteConfiguration: s3WebsiteConfig,
}
s3BucketResourceName := stableCloudformationResourceName("Site")
cfResource := template.AddResource(s3BucketResourceName, s3Bucket)
cfResource.DeletionPolicy = "Delete"
template.Outputs[OutputS3SiteURL] = &gocf.Output{
Description: "S3 Website URL",
Value: gocf.GetAtt(s3BucketResourceName, "WebsiteURL"),
}
// Represents the S3 ARN that is provisioned
s3SiteBucketResourceValue := gocf.Join("",
gocf.String("arn:aws:s3:::"),
gocf.Ref(s3BucketResourceName))
s3SiteBucketAllKeysResourceValue := gocf.Join("",
gocf.String("arn:aws:s3:::"),
gocf.Ref(s3BucketResourceName),
gocf.String("/*"))
//////////////////////////////////////////////////////////////////////////////
// 2 - Add a bucket policy to enable anonymous access, as the PublicRead
// canned ACL doesn't seem to do what is implied.
// TODO - determine if this is needed or if PublicRead is being misued
s3SiteBucketPolicy := &gocf.S3BucketPolicy{
Bucket: gocf.Ref(s3BucketResourceName).String(),
PolicyDocument: ArbitraryJSONObject{
"Version": "2012-10-17",
"Statement": []ArbitraryJSONObject{
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": ArbitraryJSONObject{
"AWS": "*",
},
"Action": "s3:GetObject",
"Resource": s3SiteBucketAllKeysResourceValue,
},
},
},
}
s3BucketPolicyResourceName := stableCloudformationResourceName("S3SiteBucketPolicy")
template.AddResource(s3BucketPolicyResourceName, s3SiteBucketPolicy)
//////////////////////////////////////////////////////////////////////////////
// 3 - Create the IAM role for the lambda function
// The lambda function needs to download the posted resource content, as well
// as manage the S3 bucket that hosts the site.
statements := CommonIAMStatements["core"]
statements = append(statements, iamPolicyStatement{
Action: []string{"s3:ListBucket"},
Effect: "Allow",
Resource: s3SiteBucketResourceValue,
})
statements = append(statements, iamPolicyStatement{
Action: []string{"s3:DeleteObject", "s3:PutObject"},
Effect: "Allow",
Resource: s3SiteBucketAllKeysResourceValue,
})
statements = append(statements, iamPolicyStatement{
Action: []string{"s3:GetObject"},
Effect: "Allow",
Resource: gocf.Join("",
gocf.String("arn:aws:s3:::"),
gocf.String(S3Bucket),
gocf.String("/"),
//.........这里部分代码省略.........
示例12: ensureConfiguratorLambdaResource
// TODO - Refactor ensure Lambdaconfigurator, then finish
// implementing the CloudWatchEvents Principal type.
func ensureConfiguratorLambdaResource(awsPrincipalName string,
sourceArn *gocf.StringExpr,
dependsOn []string,
template *gocf.Template,
S3Bucket string,
S3Key string,
logger *logrus.Logger) (string, error) {
// AWS service basename
awsServiceName := awsPrincipalToService(awsPrincipalName)
configuratorExportName := strings.ToLower(awsServiceName)
logger.WithFields(logrus.Fields{
"ServiceName": awsServiceName,
"NodeJSExportName": configuratorExportName,
}).Debug("Ensuring AWS push service configurator CustomResource")
// Use a stable resource CloudFormation resource name to represent
// the single CustomResource that can configure the different
// PushSource's for the given principal.
keyName, err := json.Marshal(ArbitraryJSONObject{
"Principal": awsPrincipalName,
"ServiceName": awsServiceName,
})
if err != nil {
logger.Error("Failed to create configurator resource name: ", err.Error())
return "", err
}
subscriberHandlerName := CloudFormationResourceName(fmt.Sprintf("%sCustomResource", awsServiceName),
string(keyName))
//////////////////////////////////////////////////////////////////////////////
// IAM Role definition
iamResourceName, err := ensureIAMRoleForCustomResource(awsPrincipalName, sourceArn, template, logger)
if nil != err {
return "", err
}
iamRoleRef := gocf.GetAtt(iamResourceName, "Arn")
_, exists := template.Resources[subscriberHandlerName]
if !exists {
logger.WithFields(logrus.Fields{
"Service": awsServiceName,
}).Debug("Including Lambda CustomResource for AWS Service")
configuratorDescription := fmt.Sprintf("Sparta created Lambda CustomResource to configure %s service",
awsServiceName)
//////////////////////////////////////////////////////////////////////////////
// Custom Resource Lambda Handler
// NOTE: This brittle function name has an analog in ./resources/index.js b/c the
// AWS Lamba execution treats the entire ZIP file as a module. So all module exports
// need to be forwarded through the module's index.js file.
handlerName := nodeJSHandlerName(configuratorExportName)
logger.Debug("Lambda Configuration handler: ", handlerName)
customResourceHandlerDef := gocf.LambdaFunction{
Code: &gocf.LambdaFunctionCode{
S3Bucket: gocf.String(S3Bucket),
S3Key: gocf.String(S3Key),
},
Description: gocf.String(configuratorDescription),
Handler: gocf.String(handlerName),
Role: iamRoleRef,
Runtime: gocf.String("nodejs"),
Timeout: gocf.Integer(30),
}
cfResource := template.AddResource(subscriberHandlerName, customResourceHandlerDef)
if nil != dependsOn && (len(dependsOn) > 0) {
cfResource.DependsOn = append(cfResource.DependsOn, dependsOn...)
}
}
return subscriberHandlerName, nil
}
示例13: export
// export marshals the API data to a CloudFormation compatible representation
func (s3Site *S3Site) export(serviceName string,
S3Bucket string,
S3Key string,
S3ResourcesKey string,
apiGatewayOutputs map[string]*gocf.Output,
roleNameMap map[string]*gocf.StringExpr,
template *gocf.Template,
logger *logrus.Logger) error {
websiteConfig := s3Site.WebsiteConfiguration
if nil == websiteConfig {
websiteConfig = &s3.WebsiteConfiguration{}
}
//////////////////////////////////////////////////////////////////////////////
// 1 - Create the S3 bucket. The "BucketName" property is empty s.t.
// AWS will assign a unique one.
if nil == websiteConfig.ErrorDocument {
websiteConfig.ErrorDocument = &s3.ErrorDocument{
Key: aws.String("error.html"),
}
}
if nil == websiteConfig.IndexDocument {
websiteConfig.IndexDocument = &s3.IndexDocument{
Suffix: aws.String("index.html"),
}
}
s3WebsiteConfig := &gocf.S3WebsiteConfigurationProperty{
ErrorDocument: gocf.String(aws.StringValue(websiteConfig.ErrorDocument.Key)),
IndexDocument: gocf.String(aws.StringValue(websiteConfig.IndexDocument.Suffix)),
}
s3Bucket := &gocf.S3Bucket{
AccessControl: gocf.String("PublicRead"),
WebsiteConfiguration: s3WebsiteConfig,
}
s3BucketResourceName := stableCloudformationResourceName("Site")
cfResource := template.AddResource(s3BucketResourceName, s3Bucket)
cfResource.DeletionPolicy = "Delete"
template.Outputs[OutputS3SiteURL] = &gocf.Output{
Description: "S3 Website URL",
Value: gocf.GetAtt(s3BucketResourceName, "WebsiteURL"),
}
// Represents the S3 ARN that is provisioned
s3SiteBucketResourceValue := gocf.Join("",
gocf.String("arn:aws:s3:::"),
gocf.Ref(s3BucketResourceName))
s3SiteBucketAllKeysResourceValue := gocf.Join("",
gocf.String("arn:aws:s3:::"),
gocf.Ref(s3BucketResourceName),
gocf.String("/*"))
//////////////////////////////////////////////////////////////////////////////
// 2 - Add a bucket policy to enable anonymous access, as the PublicRead
// canned ACL doesn't seem to do what is implied.
// TODO - determine if this is needed or if PublicRead is being misued
s3SiteBucketPolicy := &gocf.S3BucketPolicy{
Bucket: gocf.Ref(s3BucketResourceName).String(),
PolicyDocument: ArbitraryJSONObject{
"Version": "2012-10-17",
"Statement": []ArbitraryJSONObject{
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": ArbitraryJSONObject{
"AWS": "*",
},
"Action": "s3:GetObject",
"Resource": s3SiteBucketAllKeysResourceValue,
},
},
},
}
s3BucketPolicyResourceName := stableCloudformationResourceName("S3SiteBucketPolicy")
template.AddResource(s3BucketPolicyResourceName, s3SiteBucketPolicy)
//////////////////////////////////////////////////////////////////////////////
// 3 - Create the IAM role for the lambda function
// The lambda function needs to download the posted resource content, as well
// as manage the S3 bucket that hosts the site.
statements := CommonIAMStatements.Core
statements = append(statements, spartaIAM.PolicyStatement{
Action: []string{"s3:ListBucket",
"s3:ListObjectsPages"},
Effect: "Allow",
Resource: s3SiteBucketResourceValue,
})
statements = append(statements, spartaIAM.PolicyStatement{
Action: []string{"s3:DeleteObject",
"s3:PutObject",
"s3:DeleteObjects",
"s3:DeleteObjects"},
Effect: "Allow",
Resource: s3SiteBucketAllKeysResourceValue,
})
statements = append(statements, spartaIAM.PolicyStatement{
Action: []string{"s3:GetObject"},
//.........这里部分代码省略.........