How to attach an existing role to serverless.yml? - amazon-web-services

I want to attach an existing role to my serverless.yml file, I have created a role in aws console, my code works fine when I test it in aws console, but when I try to test it with the http endpoint it gives me the following:
{"message": "Internal server error"}
I think is because I did not specify any role in the serverless.yml file for the simple reason that I don't know how to do it.
Here is my serverless.yml file :
Resources:
ec2-dev-instance-status:
Properties:
Path: "arn:aws:iam::119906431229:role/lambda-ec2-describe-status"
RoleName: lambda-ec2-describe-status
Type: "AWS::IAM::Role"
functions:
instance-status:
description: "Status ec2 instances"
events:
-
http:
method: get
path: users/create
handler: handler.instance_status
role: "arn:aws:iam::119906431229:role/lambda-ec2-describe-status"
provider:
name: aws
region: us-east-1
runtime: python2.7
stage: dev
resources: ~
service: ec2
Please help.
Thank you.

According to the documentation, there's a few ways to attach existing roles to a function (or entire stack)
Role defined as a Serverless resource
resources:
Resources:
myCustRole0:
Type: AWS::IAM::Role
# etc etc
functions:
func0:
role: myCustRole0
Role defined outside of the Serverless stack
functions:
func0:
role: arn:aws:iam::0123456789:role//my/default/path/roleInMyAccount
Note that the role you use must have additional permissions to log to cloudwatch etc, otherwise you won't get logging.

Related

How to add a resource based policy to a lambda using AWS SAM

I want to create a deployment script for some lambda functions using AWS SAM. Two of those functions will be deployed into one account(account A) but will be triggered by an s3 bucket object creation event in a second account(account B). From what I know the only way to do this is by using adding a resource based policy to my lambda. But I don't know how to do that in AWS SAM. My current yaml file looks like this.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
deploy-test-s3-triggered-lambda
Parameters:
AppBucketName:
Type: String
Description: "REQUIRED: Unique S3 bucket name to use for the app."
Resources:
S3TriggeredLambda:
Type: AWS::Serverless::Function
Properties:
Role: arn:aws:iam::************:role/lambda-s3-role
Handler: src/handlers/s3-triggered-lambda.invokeAPI
CodeUri: src/handlers/s3-triggered-lambda.js.zip
Runtime: nodejs10.x
MemorySize: 128
Timeout: 60
Policies:
S3ReadPolicy:
BucketName: !Ref AppBucketName
Events:
S3NewObjectEvent:
Type: S3
Properties:
Bucket: !Ref AppBucket
Events: s3:ObjectCreated:*
AppBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Ref AppBucketName
What do I need to add to this yaml file in order to tie a resource based policy that allows for cross account access to my lambda function?
This can be done achieved with the help of AWS::Lambda::Permission using aws_cdk.aws_lambda.CfnPermission.
For example, to allow your lambda to be called from a role in another account, add the following to your CDK:
from aws_cdk import aws_lambda
aws_lambda.CfnPermission(
scope,
"CrossAccountInvocationPermission",
action="lambda:InvokeFunction",
function_name="FunctionName",
principal="arn:aws:iam::111111111111:role/rolename",
)
If your bucket and your Lambda function exist in separate accounts I don't know if it's possible to modify both of them from SAM / a single CloudFormation template.
Don't think cross account s3 event is possible with SAM, may need to go back to CFN.

Configuring logging of AWS API Gateway

I created a lambda function to upload files to s3. When testing via the AWS interface, everything works. Next I created the API Gateway and tried to make a request through ReactJs. But I get an error. I want to see what error occurs but I cannot add logs to the API Gateway. What I do.
Create API Gateway -> go to Stages-> Logs/Tracing
Try to activate checkbox Enable CloudWatch Logs but got CloudWatch Logs role ARN must be set in account settings to enable logging
Create role in IAM with next policy: AmazonS3FullAccess, AmazonAPIGatewayPushToCloudWatchLogs, AWSLambdaBasicExecutionRole
Copy the Role ARN
go to the setting of my api and try to paste to CloudWatch log role ARN. But got The role ARN does not have required permissions set to API Gateway.
Can you tell me what other settings I need?
According to this documentation (https://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-cloudwatch-logs/) after creating the Role, you need to add it to the Global AWS Api Gateway Settings (when you open the Console, there is a settings menu in the left pane) as the CloudWatch log role ARN.
Then it will use that role for all the gateways you create, so this is a one-time step.
Using a SAM template
You can automate all your deployment process using Serverless Application Model (SAM) or Serverless Framework. The following SAM template defines the Api Gateway and required configuration to enable CloudWatch Logs:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
ApiGatewayApi:
Type: AWS::Serverless::Api
DependsOn: ApiCWLRoleArn
Properties:
StageName: prod
MethodSettings:
- LoggingLevel: INFO
MetricsEnabled: True
ResourcePath: '/*' # allows for logging on any resource
HttpMethod: '*' # allows for logging on any method
Auth:
ApiKeyRequired: true # sets for all methods
ApiCWLRoleArn:
Type: AWS::ApiGateway::Account
Properties:
CloudWatchRoleArn: !GetAtt CloudWatchRole.Arn
# IAM Role for API Gateway + CloudWatch Logging
CloudWatchRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
Action: 'sts:AssumeRole'
Effect: Allow
Principal:
Service: apigateway.amazonaws.com
Path: /
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs'

Give Lambda Invoke permission to ApiGateway with one deployment

I wrote resources in my serverless.yml like below:
resources:
Resources:
RestApi :
Type : AWS::ApiGateway::RestApi
Properties :
Body : ${file(./swagger.yaml)}
LoginApiToInvokeLambda:
Type: AWS::Lambda::Permission
Properties:
FunctionName: login
Action: lambda:InvokeFunction
Principal: apigateway.amazonaws.com
When I sls deploy, below error occured:
An error occurred: LoginApiToInvokeLambda - Function not found: arn:aws:lambda:ap-northeast-1:xxxxxxxxxxxx:function:api-dev-login (Service: AWSLambda; Status Code: 404; Error Code: ResourceNotFoundException
In the initial deployment, I thought that permissions were set before creating lambda functions. Therefore, I commented out LoginApiToInvokeLambda in my serverless.yml. I sls deploy again, it succeeded. But ApiGateway does not have permission to invoke lambda. After that I restored the commented out part, and sls deploy. Finally I was able to give ApiGateway the permission of Lambda invoke.
Is there a way to accomplish this at the same time?
You can use DependsOn functionality of CloudFormation in the resources section.
resources:
Resources:
# ...
LoginApiToInvokeLambda:
Type: AWS::Lambda::Permission
DependsOn: LoginLambdaFunction
Properties:
FunctionName: login
Action: lambda:InvokeFunction
Principal: apigateway.amazonaws.com
I've assumed your lambda function key is login which gets translated to LoginLambdaFunction. If not, check the serverless documentation on how the resources get named.
In short serverless translates your configuration to a CloudFormation template, and the resources section allows you to customise what gets generated, which is why you can use DependsOn to solve your issue.

Attach a preexisting role in template.yml file while creating sam application through console

I am trying to create a sam application with a pre existing role through sam-cli.By default the sam clil creates new user roles with basic lambda exuection policies ,but as i want to run x-ray on my sam application i would want application to be created with existing user role.
Here is my template.yml
AWSTemplateFormatVersion : '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
POCLambdaExecutionRole:
Type: 'AWS::IAM::Role'
SAMLocal:
Type: AWS::Serverless::Function
Properties:
Handler: SAMLocal.lambda_handler
Runtime: python2.7
TracingConfig:
Mode: Active
Environment:
Variables:
dev_table: "MessageQueue"
Events:
SAMLocal:
Type: Api
Properties:
Path: /
Method: GET
SAMLocal1:
Type: AWS::Serverless::Function
Properties:
Handler: SAMLocal.lambda_handler
Runtime: python2.7
How can i achieve the same .
found this article on stack overflow but does not really helps my casue Associate existing IAM role with EC2 instance in CloudFormation
you need to put existing role in your yaml file in ARN format
role: arn:aws:iam::XXXXXX:role/role
you can either set role or permission. If you do not define role for your funcition, SAM will create one role for every function. by default, it will scope for each funcition individually.
Declare Role outside your function in the fashion i have described in my solution role: arn:aws:iam::XXXXXX:role/role
Check THIS

Deploy AWS SAM functions using already created roles

When trying to deploy to AWS using AWS SAM CLI my Lambda functions using the following script:
aws cloudformation deploy --template-file /Users/ndelvalle/Projects/foo/functions/packaged-template.yaml --stack-name foo --region sa-east-1 --capabilities CAPABILITY_IAM --no-fail-on-empty-changeset
I got the following error in the stack events:
API: iam:CreateRole User: arn:aws:iam::user/nico is not authorized to perform: iam:CreateRole on resource
This is because I don't have role creation permissions on my account. That is why I wonder if there is a way to define pre-created roles to my lambdas, so the script does not need to create the role.
There is more information needed to answer this for you. Many different permissions come into play when deploying with SAM. I implemented SAM template for my company to manage our lambda stacks. We needed to give our Java Developers working on the stacks the same permissions that the SAM template implicitly and explicitly creates, beyond just creating roles. For this we created several special groups in IAM that we attached our Serverless Devs too. It is possible to assign specific predefined roles to Lambdas, https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction. If you define a role in the template, it does not automatically create a role. However, if you are declaring other resources like Api Gateway and DynamoDB, you will still run into problems.
So long story short, if you are working with SAM its better you have your Sys admin give you permissions to Create role, and you will need other permissions as well, or have the deployment of the SAM template done by a Job runner like Jenkins (that has the permissions). It it is too permissive for your team/company, maybe SAM is not a good solution... Best to switch to something like pure CloudFormation and abandon a developer oriented workflow. Somethings to think about, hope its helpful.
You can use the Role property as mentioned in the docs for AWS::Serverless::Function
A sample template which creates a new lambda without creating a new role,
Transform: AWS::Serverless-2016-10-31
Description: >
sam-app
Sample SAM Template for sam-app
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 3
Tracing: Active
Api:
TracingEnabled: True
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello-world/
Handler: app.lambdaHandler
Runtime: nodejs18.x
Role: <ARN of ROLE>
Architectures:
- x86_64
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: get
Metadata: # Manage esbuild properties
BuildMethod: esbuild
BuildProperties:
Minify: true
Target: "es2020"
Sourcemap: true
EntryPoints:
- app.ts
Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
HelloWorldFunction:
Description: "Hello World Lambda Function ARN"
Value: !GetAtt HelloWorldFunction.Arn
HelloWorldFunctionIamRole:
Description: "Implicit IAM Role created for Hello World function"
Value: !GetAtt HelloWorldFunctionRole.Arn