Error parsing parameter '--parameters': Expected: '=', received: 'P' - amazon-web-services

I am working with aws cli cloudformation. While using the JSON parameters file along with yml template, I keep getting the error. I tried using create stack update stack as well as the change set.
Error parsing parameter '--parameters': Expected: '=', received: 'P' for input:
- ParameterKey: FunctionName
^
ParameterValue: taskaplambda
- ParameterKey: MemorySize
ParameterValue: 512
- ParameterKey: Timeout
ParameterValue: 5
Where my command is:
aws cloudformation update-stack --stack-name apstack --template-body file://templates/cflambdatemplate.yaml --parameters file://params/param.json
And my param.json is:
[
{
"ParameterKey": "FunctionName",
"ParameterValue": "taskaplambda"
},
{
"ParameterKey": "MemorySize",
"ParameterValue": 512
},
{
"ParameterKey": "Timeout",
"ParameterValue": 5
}
]
This is my YAML file
cflambdatemplate.yaml
Transform: AWS::Serverless-2016-10-31
Resources:
tasklambda:
Type: AWS::Serverless::Function
Properties:
FunctionName: !Ref FunctionName
Handler: lambda_function.lambda_handler
MemorySize: !Ref MemorySize
Role:
Fn::GetAtt:
- "tasklambdarole"
- "Arn"
Runtime: python3.7
Timeout: !Ref Timeout
CodeUri:
Bucket: taskapbucket
Key: apbuild/lambda_function.zip
tasklambdarole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
-
Effect: "Allow"
Principal:
Service:
- "lambda.amazonaws.com"
Action:
- "sts:AssumeRole"
Path: "/"
taskPolicies:
Type: "AWS::IAM::Policy"
Properties:
PolicyName: "root"
PolicyDocument:
Version: "2012-10-17"
Statement:
-
Effect: "Allow"
Action: "*"
Resource: "*"
Roles:
-
Ref: "tasklambdarole"
Parameters:
FunctionName:
Type: String
MinLength: '3'
MaxLength: '18'
MemorySize:
Type: Number
MinValue: '128'
MaxValue: '1024'
Timeout:
Type: Number
MinValue: '1'
MaxValue: '15'
I have been trying this with every possibility, but it keeps giving me an error.

Just able to create everything you needed through aws CLI:
I'm using the same yaml file and json template of parameter and not getting any error. Below is the only change that I did in param.json :
[
{
"ParameterKey": "FunctionName",
"ParameterValue": "taskaplambda"
},
{
"ParameterKey": "MemorySize",
"ParameterValue": "512"
},
{
"ParameterKey": "Timeout",
"ParameterValue": "5"
}
]
You need to convert the Number to String, It's because CloudFormation parameter types don't map to JSON types, so the CLI expects everything to be passed as string.

Related

ARN as a parameter in Cloud Formation Stack

I wanted to use the ARN as parameter input to cloudformation stack resources EventRuleRegion1 - Target as well as EventBridgeIAMrole , but it is not working. when i call with Ref function
Original ARN
arn:aws:events:ap-southeast-2:123456789123:event-bus/central-eventbus-sydney
When i give the arn directly in code its working fine.
Code
AWSTemplateFormatVersion: 2010-09-09
Parameters:
EventBridgeName:
Description: Enter the Event Bridge Name
Type: String
Default: ec2-lifecycle-events
EventBusName:
Description: Enter the Central Event Bus Name
Type: String
Default: central-eventbus-sydney
EventBusArn:
Description: Enter the ARN of Central Event Bus
Type: String
Default: arn:aws:events:ap-southeast-2:123456789123:event-bus/central-eventbus-sydney
Monitoringaccount:
Description: Enter the Monitoring AWS account number
Type: String
Default: 123456789123
Resources:
EventRuleRegion1:
Type: AWS::Events::Rule
Properties:
Description: Event rule to send events to monitoring account event bus
EventBusName: default
EventPattern:
source:
- aws.ec2
detail-type:
- "EC2 Instance State-change Notification"
detail:
state:
- "running"
- "stopped"
- "terminated"
Name: !Ref EventBridgeName
State: ENABLED
Targets:
- Arn: >-
- !Join [ "", [ !Sub "arn:aws:events:${AWS::Region}:123456789123:event-bus/",!Ref EventBusName ] ]
Id: !Ref EventBusName
RoleArn: !GetAtt
- EventBridgeIAMrole
- Arn
EventBridgeIAMrole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service: !Sub events.amazonaws.com
Action: 'sts:AssumeRole'
Path: /
Policies:
- PolicyName: PutEventsDestinationBus
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- 'events:PutEvents'
Resource:
- >-
- !Join [ "", [ !Sub "arn:aws:events:${AWS::Region}:123456789123:event-bus/",!Ref EventBusName ] ]
Error
Parameter - !Join [ "", [ !Sub "arn:aws:events:${AWS::Region}:123456789123:event-bus/",!Ref EventBusName ] ] is not valid. Reason: Provided Arn is not in correct format. (Service: AmazonCloudWatchEvents; Status Code: 400; Error Code: ValidationException; Request ID: 0d52a1d6-095e-44f7-9455-b7481dc4fb8d; Proxy: null)
The use of >- will result in literal strings, not evaluation of your CFN functions (join, ref). It should be:
Targets:
- Arn: !Join [ "", [ !Sub "arn:aws:events:${AWS::Region}:123456789123:event-bus/",!Ref EventBusName ] ]

Json format error in cloud formation template

I'm getting the error below from my cloud formation template. It happens when using json and pure yaml.
error
Resource handler returned message: "Invalid request provided: JSON not well-formed. at Line: 13, Column: 10 (Service: Ssm, Status Code: 400,
template with json
AWSTemplateFormatVersion: "2010-09-09"
Description: "AWS CloudFormation Template for Response Plans"
Parameters:
Environment:
Type: String
Domain:
Type: String
Team:
Type: String
NotificationARN:
Type: AWS::SSM::Parameter::Value<String>
Default: /sandbox06/Topics/PolicyData/arn
Resources:
UpdateAliasResponsePlan:
Type: AWS::SSMIncidents::ResponsePlan
Properties:
Actions:
- SsmAutomation:
RoleArn: !Ref Role
DocumentName: UpdateAliasDocument
# ActionType: UpdateAlias
DisplayName: "UpdateLambdaAlias"
# Engagements:
# Engagements
IncidentTemplate:
Impact: 3
NotificationTargets:
- SnsTopicArn:
Ref: NotificationARN
Summary: "String"
Title: "String"
Name: "UpdateLambdaAlias"
Tags:
- Key: "Team"
Value: !Ref Team
- Key: "Domain"
Value: !Ref Domain
- Key: "Environment"
Value: !Ref Environment
UpdateAliasDocument:
Type: AWS::SSM::Document
Properties:
Content: |
{
"schemaVersion": "2.2",
"parameters": {
"Environment": { "type": "string"},
"Domain": { "type": "string"},
"Team": { "type": "string"},
"NotificationARN": { "type": "string", "default": "/sandbox06/Topics/PolicyData/arn"}
},
"mainSteps": [
{ "action": "aws:runShellScript",
"name": "runCommands",
"inputs": {
"runCommand": ["aws lambda update-functionconfiguration --function-name $FunctionArn --version $FunctionVersion"]
}
]
}
Role:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action: sts:AssumeRole
Path: /
Policies:
- PolicyName: UpdateAliasPolicy
PolicyDocument:
Statement:
- Effect: Allow
Action:
- lambda:UpdateFunctionConfiguration
Resource:
- !Sub arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:${Environment}-*
template with yaml
AWSTemplateFormatVersion: "2010-09-09"
Description: "AWS CloudFormation Template for Response Plans"
Parameters:
Environment:
Type: String
Domain:
Type: String
Team:
Type: String
NotificationARN:
Type: AWS::SSM::Parameter::Value<String>
Default: /sandbox06/Topics/PolicyData/arn
Resources:
UpdateAliasResponsePlan:
Type: AWS::SSMIncidents::ResponsePlan
Properties:
Actions:
- SsmAutomation:
RoleArn: !Ref Role
DocumentName: UpdateAliasDocument
# ActionType: UpdateAlias
DisplayName: "UpdateLambdaAlias"
# Engagements:
# Engagements
IncidentTemplate:
Impact: 3
NotificationTargets:
- SnsTopicArn:
Ref: NotificationARN
Summary: "String"
Title: "String"
Name: "UpdateLambdaAlias"
Tags:
- Key: "Team"
Value: !Ref Team
- Key: "Domain"
Value: !Ref Domain
- Key: "Environment"
Value: !Ref Environment
UpdateAliasDocument:
Type: AWS::SSM::Document
Properties:
Content:
schemaVersion: "2.2"
parameters:
- name: FunctionVersion
type: "String"
defaultValue: "1"
- name: FunctionArn
type: "String"
mainSteps:
- action: aws:runShellScript
name: "runCommand"
inputs:
runCommand: "aws lambda update-function-configuration --function-name $FunctionArn --version $FunctionVersion"
Role:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action: sts:AssumeRole
Path: /
Policies:
- PolicyName: UpdateAliasPolicy
PolicyDocument:
Statement:
- Effect: Allow
Action:
- lambda:UpdateFunctionConfiguration
Resource:
- !Sub arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:${Environment}-*
Another YAML Version
AWSTemplateFormatVersion: "2010-09-09"
Description: "AWS CloudFormation Template for Response Plans"
Parameters:
Environment:
Type: String
Domain:
Type: String
Team:
Type: String
NotificationARN:
Type: AWS::SSM::Parameter::Value<String>
Default: /sandbox06/Topics/PolicyData/arn
Resources:
UpdateAliasResponsePlan:
Type: AWS::SSMIncidents::ResponsePlan
Properties:
Actions:
- SsmAutomation:
RoleArn: !Ref Role
DocumentName: UpdateAliasDocument
# ActionType: UpdateAlias
DisplayName: "UpdateLambdaAlias"
# Engagements:
# Engagements
IncidentTemplate:
Impact: 3
NotificationTargets:
- SnsTopicArn:
Ref: NotificationARN
Summary: "String"
Title: "String"
Name: "UpdateLambdaAlias"
Tags:
- Key: "Team"
Value: !Ref Team
- Key: "Domain"
Value: !Ref Domain
- Key: "Environment"
Value: !Ref Environment
UpdateAliasDocument:
Type: AWS::SSM::Document
Properties:
Content:
schemaVersion: "2.2"
parameters:
- name: FunctionVersion
type: "String"
defaultValue: "1"
- name: FunctionName
type: "String"
mainSteps:
- name: UpdateLambdaAlias
action: aws:executeAWSApi
inputs:
Service: "lambda"
Api: UpdateFunctionConfiguration
FunctionName: $FunctionName
FunctionVersion: $FunctionVersion
Role:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action: sts:AssumeRole
Path: /
Policies:
- PolicyName: UpdateAliasPolicy
PolicyDocument:
Statement:
- Effect: Allow
Action:
- lambda:UpdateFunctionConfiguration
Resource:
- !Sub arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:${Environment}-*
You're getting the error when it tries to resolve the SSM parameters. It is a 400 error, so it may be that you don't have permission to retrieve the parameter from SSM. In this case it is looking for /sandbox06/Topics/PolicyData/arn so verify that the account you are using to create the stack has permission to retrieve that parameter. This article shows the permissions needed.
If so, also verify that the value of that parameter in SSM would result in a valid template if you pasted it into your template. Verify that the SSM parameter is of type String, as AWS::SSM::Parameter::Value<String> is
A Systems Manager parameter whose value is a string. This corresponds
to the String parameter type in Parameter Store.
That link also mentions the following and gives an alternative if you are want to fetch a secure string:
AWS CloudFormation does not support defining template parameters as
SecureString Systems Manager parameter types.
Also, it may be that you need to format the default to not start with a slash. This page shows an example that does not start with a slash, or for hierarchical parameters that do begin with a slash, it may need to be in single quotes (Example 2 shows it that way)
The problem was with the way I was defining the parameters. I needed to remove the name key.
replace
UpdateAliasDocument:
Type: AWS::SSM::Document
Properties:
Content:
schemaVersion: "2.2"
parameters:
- name: FunctionVersion
type: "String"
defaultValue: "1"
- name: FunctionName
type: "String"
mainSteps:
- name: UpdateLambdaAlias
action: aws:executeAWSApi
inputs:
Service: "lambda"
Api: UpdateFunctionConfiguration
FunctionName: $FunctionName
FunctionVersion: $FunctionVersion
with
UpdateAliasDocument:
Type: AWS::SSM::Document
Properties:
Content:
schemaVersion: "2.2"
parameters:
FunctionVersion
type: "String"
defaultValue: "1"
FunctionName
type: "String"
mainSteps:
- name: UpdateLambdaAlias
action: aws:executeAWSApi
inputs:
Service: "lambda"
Api: UpdateFunctionConfiguration
FunctionName: $FunctionName
FunctionVersion: $FunctionVersion

Can't link lambda with cloudwatch event trigger

I'm creating an ASG group which has a lifecyclehook for termination:
LifecycleHook:
Type: AWS::AutoScaling::LifecycleHook
Properties:
AutoScalingGroupName: !Ref NodeGroup
DefaultResult: CONTINUE
HeartbeatTimeout: 60
LifecycleHookName: !Sub "${AWS::StackName}-lifecycle-hook"
LifecycleTransition: autoscaling:EC2_INSTANCE_TERMINATING
Now I create a lambda function as well:
LambdaCreation:
Type: "AWS::Lambda::Function"
Properties:
Handler: "lambda_function.lambda_handler"
Environment:
Variables:
aws_region : !Ref AWSRegion
Role: !GetAtt LambdaExecutionRole.Arn
Code:
S3Bucket: !Ref LambdaCodeBucket
S3Key: "lambda-functions/function.zip"
Runtime: "python3.6"
Timeout: 60
On cloudwatch events, i created a rule for said event:
CloudwatchEvent:
Type: AWS::Events::Rule
Properties:
Description: ASG scale-in event to lambda
EventPattern: {
"source": [
"aws.autoscaling"
],
"detail-type": [
"EC2 Instance-terminate Lifecycle Action"
],
"detail": {
"AutoScalingGroupName":
[
{
"Fn::ImportValue" :
{
"Fn::Sub" : "${RootStackName}-nodes-asg-name"
}
}
]
}
}
State: ENABLED
Targets:
-
Arn:
!GetAtt LambdaCreation.Arn
Id:
!Ref LambdaCreation
But the lambda is never triggered.
Now, on AWS console I don't see a trigger on the designer. But if i add manually a cloudwatch trigger for the created rule, it starts working...
Why is the trigger on the lambda side not created? What am I missing?
Thanks all!
I faced the exact same frustration. Only difference is that I was using terraform but that's irrelavant.
You are missing this:
{
"Type" : "AWS::Lambda::Permission",
"Properties" : {
"Action" : String,
"EventSourceToken" : String,
"FunctionName" : String,
"Principal" : String,
"SourceAccount" : String,
"SourceArn" : String
}
}
The reason the "manual way" works because it creates the trigger AND the permission. When you provision stuff using IaC tools like Cloudformation/terraform, you need to explicitly specify this Lambda permission object.
The below code snippet creates a lambda function and creates a cloudwatch event to trigger the lambda function with necessary privileges.
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: root
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- logs:*
Resource: arn:aws:logs:*:*:*
- Effect: Allow
Action:
- s3:ListBucket
Resource: !Join [ '', [ 'arn:aws:s3:::', !Ref LambdaS3Bucket ] ]
- Effect: Allow
Action:
- s3:GetObject
Resource: !Join [ '', [ 'arn:aws:s3:::', !Ref LambdaS3Bucket, '/*' ] ]
- Effect: Allow
Action:
- sts:GetCallerIdentity
Resource: '*'
LambdaFunction:
Type: "AWS::Lambda::Function"
Properties:
Description: "Lambda function"
FunctionName: !Ref LambdaFunctionName
Handler: !Ref LambdaHandler
Runtime: !Ref LambdaRuntime
Timeout: !Ref LambdaTimeout
MemorySize: !Ref LambdaMemorysize
Role: !GetAtt LambdaExecutionRole.Arn
Code:
S3Bucket: !Ref LambdaS3Bucket
S3Key: !Ref LambdaS3BucketKey
Environment:
Variables:
time_interval_in_hours: !Ref TimeIntervalInHours
DependsOn: LambdaExecutionRole
CleanupEventRule:
Type: AWS::Events::Rule
Properties:
Description: "Cloudwatch Rule"
ScheduleExpression: !Ref CloudwatchScheduleExpression
State: !Ref CloudWatchEventState
Targets:
- Arn: !Sub ${LambdaFunction.Arn}
Id: "CleanupEventRule"
DependsOn: LambdaFunction
LambdaSchedulePermission:
Type: AWS::Lambda::Permission
Properties:
Action: 'lambda:InvokeFunction'
FunctionName: !Sub ${LambdaFunction.Arn}
Principal: 'events.amazonaws.com'
SourceArn: !Sub ${CleanupEventRule.Arn}
DependsOn: LambdaFunction

AWS StateMachine for Lambda, cloud formation syntax

I'm trying to come up with a CloudFormation template that includes
API Gateway
Invokes a StateMachine through the API Gateway
StateMachine in turn contains a lambda function
In essence what I'm try to do is the following
https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-api-gateway.html
However I'm stuck in coming up with the Cloud Formation Template (.yaml) that will deploy this. So far this is what I have
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
Post:
Type: AWS::Serverless::Function
Properties:
FunctionName: UserBase-fnUsers
Handler: UsersHandler.getUsers
Runtime: nodejs6.10
Policies: [AmazonDynamoDBReadOnlyAccess, AmazonS3ReadOnlyAccess]
Environment:
Variables:
S3_BUCKET: UserBase-Users-bucket
UsersTable: UserBase-Users-tblUsers
Events:
GetUsers:
Type: Api
Properties:
Path: /UserBase/Users
Method: post
Options:
Type: AWS::Serverless::Function
Properties:
FunctionName: UserBase-fnUsers-Options
Handler: UsersHandler.getOptions
Runtime: nodejs6.10
Events:
GetOptions:
Type: Api
Properties:
Path: /UserBase/Users
Method: options
UsersTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: UserBase-Users-tblUsers
AttributeDefinitions:
- AttributeName: Id
AttributeType: S
KeySchema:
- AttributeName: Id
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 5
StreamSpecification:
StreamViewType: KEYS_ONLY
StatesExecutionRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Service:
- !Sub states.${AWS::Region}.amazonaws.com
Action: "sts:AssumeRole"
Path: "/"
Policies:
- PolicyName: StatesExecutionPolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- "lambda:InvokeFunction"
Resource: "*"
UpdateShoppingPath:
Type: "AWS::StepFunctions::StateMachine"
Properties:
DefinitionString:
!Sub
- |-
{
"Comment": "State machine to update the shopping path",
"StartAt": "UpdatePath",
"States": {
"UpdatePath": {
"Type": "Task",
"Resource": "${lambdaArn}",
"End": true
}
}
}
- {lambdaArn: !GetAtt [ Post, Arn ]}
RoleArn: !GetAtt [ StatesExecutionRole, Arn ]
UserBaseUsers:
Type: "AWS::ApiGateway::Resource"
I'm stuck with the last piece, basically on how to link the ApiGateway to the StateMachine. On a side note is there any way for me to generate the cloud formation template (.yaml or json) from an existing deployment in AWS?
I'm not an expert with yaml, but I did some configuration with json CloudFormation and as far as I have read it's quite easy to translate.
In the past I've been stuck like you, and here's my post and my solution
What you need to do to start the execution of a Step Functions is to do a HTTP Post to arn:aws:apigateway:${region}:states:action/StartExecution passing as json object [docs]:
{
input: __input__,
stateMachineArn: __arn__
}
In short, in your AWS::ApiGateway::Method, you have to set an HTTP integration to arn:aws:apigateway:${region}:states:action/StartExecution and a requestTemplate that builds the json object I mentioned.
For reference, here my json cloudformation example:
"FooRequest": {
"DependsOn": ["FooStepMachine"],
"Type": "AWS::ApiGateway::Method",
"Properties": {
"HttpMethod": "POST",
"Integration": {
"Type": "AWS",
"Credentials": {
"Fn::GetAtt": ["FooRole",
"Arn"]
},
"IntegrationHttpMethod": "POST",
"Uri": {
"Fn::Join": ["",
["arn:aws:apigateway:",
{
"Ref": "AWS::Region"
},
":states:action/StartExecution"]]
},
"IntegrationResponses": [{
"StatusCode": 200
},
{
"StatusCode": 401
}],
"RequestTemplates": {
"application/json": {
"Fn::Sub": ["{\"input\": \"$util.escapeJavaScript($input.json('$'))\",\"stateMachineArn\": \"${arn}\"}",
{
"arn": {
"Ref": "FooStepMachine"
}
}]
}
}
}
}
}

AWS Create Cloudformation log alert for Lambda

I want to create an alert if something goes wrong with Lambda function especially when lambda throws an exception. I am planning to configure SNS topic to send a message if that alert is triggered.
All lambdas are created using CloudFormation scripts, so I am searching for a CloudFormation template to configure alarms on CloudWatch logs. I was not able to find a good/working sample. Sample code below .
{
"AWSTemplateFormatVersion" : "2010-09-09",
"Description" : "AWS CloudTrail API Activity Alarm Template for CloudWatch Logs",
"Parameters" : {
"LogGroupName" : {
"Type" : "String",
"Default" : "CloudTrail/DefaultLogGroup",
"Description" : "Enter CloudWatch Logs log group name. Default is CloudTrail/DefaultLogGroup"
},
"Email" : {
"Type" : "String",
"Description" : "Email address to notify when an API activity has triggered an alarm"
}
},
"Resources" : {
"SecurityGroupChangesAlarm": {
"Type": "AWS::CloudWatch::Alarm",
"Properties": {
"AlarmName" : "CloudTrailSecurityGroupChanges",
"AlarmDescription" : "Alarms when an API call is made to create, update or delete a Security Group.",
"AlarmActions" : [{ "Ref" : "AlarmNotificationTopic" }],
"MetricName" : "SecurityGroupEventCount",
"Namespace" : "CloudTrailMetrics",
"ComparisonOperator" : "GreaterThanOrEqualToThreshold",
"EvaluationPeriods" : "1",
"Period" : "300",
"Statistic" : "Sum",
"Threshold" : "1"
}
},
"AlarmNotificationTopic": {
"Type": "AWS::SNS::Topic",
"Properties": {
"Subscription": [
{
"Endpoint": { "Ref": "Email" },
"Protocol": "email"
}
]
}
}
}
}
In order to do this, we need to create a subscription filter on the log group for that lambda with FilterPattern: "Exception"
So whenever there is an Exception word in log message it will trigger a monitor lambda.
Following is a cloudformation template in YAML that I have written
Resources:
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: 'AllowLambdaAccess'
PolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Effect: "Allow"
Resource:
Fn::Join:
- ''
- - 'arn:aws:logs:'
- Ref: AWS::Region
- ':'
- Ref: AWS::AccountId
- ':log-group:/aws/lambda/*'
- Action:
- ec2:DescribeNetworkInterfaces
- ec2:CreateNetworkInterface
- ec2:DeleteNetworkInterface
Effect: "Allow"
Resource: "*"
RoleName: !Sub "${AWS::StackName}-LambdaExecutionRole"
SubscriptionFilter:
Type: "AWS::Logs::SubscriptionFilter"
DependsOn: "LambdaInvokePermission"
Properties:
LogGroupName: !Sub "/aws/lambda/${LogGroupName}"
FilterPattern: "Exception"
DestinationArn:
Fn::GetAtt:
- "LambdaFunction"
- "Arn"
LambdaFunction:
Type: 'AWS::Lambda::Function'
Properties:
Code:
S3Bucket: !Ref S3BucketName
S3Key: !Ref ZipFile
Description: Monitor Lambda Function
Handler: 'index.handler'
MemorySize: 1536
Role: !GetAtt
- LambdaExecutionRole
- Arn
Runtime: nodejs6.10
Environment:
Variables:
SMTP_SERVER: !Ref SMTPServer
SMTP_PORT: !Ref SMTPPort
EMAIL_FROM: !Ref FromEmail
EMAIL_TO: !Ref ToEmail
Timeout: 300
FunctionName: !Sub "${AWS::StackName}-LambdaFunction"
VpcConfig:
SecurityGroupIds: !Split [ ",", !Ref SecurityGroupId ]
SubnetIds: !Split [ ",", !Ref SubnetIds ]
DependsOn:
- LambdaExecutionRole
LambdaInvokePermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref "LambdaFunction"
Action: "lambda:InvokeFunction"
Principal: !Sub "logs.${AWS::Region}.amazonaws.com"
SourceArn:
Fn::Join:
- ''
- - 'arn:aws:logs:'
- Ref: AWS::Region
- ':'
- Ref: AWS::AccountId
- !Sub ':log-group:/aws/lambda/${LogGroupName}*'