Pépin Rémi, Ensai, 2025
remi.pepin@insee.fr
Cas d'un service classique type web service
Cas d'une fonction as a Service
✅ Avantages
❌ Désavantages possible
import json
import os
print('Loading function')
def lambda_handler(event, context):
print("Received event: " + json.dumps(event, indent=2))
print("value1 = " + event['key1'])
print(os.getenv("foo"))
return event['key1'] # Echo back the first key value
class LambdaStack(TerraformStack):
def __init__(self, scope: Construct, id: str):
super().__init__(scope, id)
AwsProvider(self, "AWS", region="us-east-1")
# Packaging du code
code = TerraformAsset(
self, "code",
path="./lambda",
type=AssetType.ARCHIVE
)
# Create Lambda function
lambda_function = LambdaFunction(self,
"lambda",
function_name="first_lambda",
runtime="python3.8",
memory_size=128,
timeout=60,
role="arn:aws:iam::147552475298:role/LabRole",
filename= code.path,
handler="lambda_function.lambda_handler",
environment={"variables":{"foo":"bar"}}
)
app = App()
LambdaStack(app, "cdktf_lambda")
app.synth()
{
"Records": [
{
"messageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78",
"receiptHandle": "MessageReceiptHandle",
"body": "Hello from SQS!", // <<==== event ici, souvent un objet json (clé:valeur)
"attributes": {
"ApproximateReceiveCount": "1",
"SentTimestamp": "1523232000000",
"SenderId": "123456789012",
"ApproximateFirstReceiveTimestamp": "1523232000001"
},
"messageAttributes": {},
"md5OfBody": "{{{md5_of_body}}}",
"eventSource": "aws:sqs",
"eventSourceARN": "arn:aws:sqs:us-east-1:123456789012:MyQueue",
"awsRegion": "us-east-1"
}
]
}
class LambdaStack(TerraformStack):
def __init__(self, scope: Construct, id: str):
super().__init__(scope, id)
AwsProvider(self, "AWS", region="us-east-1")
# Packaging du code
code = TerraformAsset(...)
# Create Lambda function
lambda_function = LambdaFunction(...)
# Create SQS queue
queue = SqsQueue(
self,
"queue",
name="input_queue",
visibility_timeout_seconds=60
)
# Link SQS as Lambda's source
LambdaEventSourceMapping(
self, "event_source_mapping",
event_source_arn=queue.arn,
function_name=lambda_function.arn
)
app = App()
LambdaStack(app, "cdktf_lambda")
app.synth()
import json
import boto3
from datetime import datetime
sqs = boto3.client('sqs') #client is required to interact with sqs
def lambda_handler(event, context):
# event provenant d'une file SQS
data = int(json.loads(event["Records"][0]["body"])["data"])
sqs.send_message(
QueueUrl="https://sqs.us-east-1.amazonaws.com/675696485075/lab-output-queue",
MessageBody=json.dumps({"body" : data})
)
return {
'statusCode': 200,
'body': data
}
Objectif