0%
April 20, 2025

"In-line" Policies via Serverless.yml: ① Self-Invokation ② s3 GetObject

aws

lambda

serverless

Self-Invokation

Usecase

In a regular server we can return a response to the requester and continue to run a slightly time consuming task in the background (like making additional request in another thread).

But this is not possible in lambda functions because the execution of the function will be brought to an halt once the lambda function returns.

In this regard, before our controller returns, we can invoke the same function again to a specific endpoint to delegate the task (so that we don't need to set up another backend).

However, for any resource to invoke any lambda function (resources are like loadbalancer, ECS task and lambda function), we need a policy on that resource.

Luckily because our function invokes itself, the lambda function itself can define the policy we need in serverless.yml.

How to do self-invokation?

Please refer to my previous article.

Policy in serverless.yml

Take my own project as an example, the line 10-15 define a policy that allows the invokation of the function itself.

Here we have followed the naming convention of serverless framework in nodejs.

1service: alice-timetable-kotlin
2package:
3  individually: true
4  artifact: build/libs/function.jar
5provider:
6  name: aws
7  region: ap-northeast-1
8  stage: dev
9  runtime: java17
10  iamRoleStatements:
11    - Effect: Allow
12      Action:
13        - lambda:InvokeFunction
14      Resource:
15        - Fn::Sub: arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${self:service}-${self:provider.stage}-api
16functions:
17  api:
18    timeout: 900
19    memorySize: 2048
20    handler: dev.james.alicetimetable.LambdaHandler
21    snapStart: true
22    environment:
23      IS_LAMBDA: true
24      SPRING_PROFILES_ACTIVE: dev
25      MAIN_CLASS: dev.james.alicetimetable.AliceTimetableApplicationKt
26    events:
27      - http: ANY /
28      - http: ANY /{proxy+}
29
30custom:
31  scriptable:
32    hooks:
33      "before:package:createDeploymentArtifacts": >
34        docker run --rm
35        -v $(pwd):/app
36        -w /app
37        gradle:jdk17
38        gradle lambdaJar
39
40plugins:
41  - serverless-scriptable-plugin

S3 GetObject Permission

The Policy
1provider:
2  name: aws
3  runtime: nodejs18.x
4  stage: dev
5  region: ap-southeast-2
6  iamRoleStatements:
7    - Effect: Allow
8      Action:
9        - s3:GetObject
10      Resource: arn:aws:s3:::<bucket-name>/*