Moving Laravel Artisan Commands To AWS Lambda
Let’s say, we’re running a Laravel application on AWS with Auto-scaling configured and there are some artisan commands that runs periodically to do certain jobs. There might be jobs that are long running and resource hungry. To remedy this problem, we can decouple such commands from application server by moving them into Lambda function. For example, we have a artisan command to run in every minutes that marks OTPs as expired after a predefined time period. To run that using AWS Lambda rather than in application server let us create a lambda function to do so.
Steps:
Login into AWS Console, Under Services > Compute Click “Lambda”
Click Create function. We will create a function from scratch. Click Author from scratch. Give that function a name, let’s say updateExpiredOtpStatus, select your preferred runtime, here I selected Python 3.8 since we will code in Python. Keep rest as it is and finally click Create function.
You’ll be redirected to function editor and configuration page. Now before writing any code first we want our lambda function to access resources e.g. RDS MySQL that are running inside a VPC. By default our newly created lambda function can’t access VPC. To enable that create a new IAM role e.g. AWSLambdaVPCAccessRole with AWSLambdaVPCAccessExecutionRole managed policy. Then look for Execution role section, click Edit, update existing role with newly created role. Click Save.
Fell free to update Basic Settings i.e. Timeout and Memory that your function needs to do certain works. Now, scroll down and look for VPC section. Click Edit right to VPC section and then in next screen you’ll be asked to select a VPC connection. Click Custom VPC and select your VPC, subnets and security groups from dropdown. And then click Save.
Reference:
Now, we’re all set for writing code inside code editor under Function code section.
Once we’re done with writing code, save it and test it to check whether it’s working as expected or not.
Finally, let’s configure the function to run in every minutes or whatever as per your business logic. Under Services menu click CloudWatch, click Rules, under Event Source select Schedule, select Fixed rate of, put any value of your preference in input box. Under Targets section select lambda function as Target and then select updateExpiredOtpStatus.
Click Configure details.
Give that Rule a name e.g. OtpExpirationSchedule and then click Create rule.
Your rule created and the lambda function will get called in every ‘x’ minutes as configured. And we’re done.
Happy Coding!