Releasing a Laravel app in Lambda using Serverless framework
As the title says, we intend to avoid using an instance to release our app. To do that we are going to use:
- Laravel (https://laravel.com/)
- Bref (https://bref.sh/)
- Serverless (https://www.serverless.com/)
- AWS Lambda (https://aws.amazon.com/lambda/)
Install Bref
First, we need to add Bref to our project.
1composer require bref/bref bref/laravel-bridge --update-with-dependencies
then we publish the package options. It will generate the serverless.yml
file.
1php artisan vendor:publish --tag=serverless-config
After publishing it, we are going to make some small changes to the serverless.yml
file that is in your app root folder:
Configuring Serverless Framework
First, we will add some tags, so we can easily find them in our AWS infrastructure:
1provider:2 ...3 stackTags:4 ManagerBy: serverless5 Role: "lambda deploy"6 Project: self:service7 Environment: ${opt:stage, self:provider.stage}
Now we will add the bucket where our deployment files will be stored.
1provider:2 ...3 deploymentBucket:4 name: maurobaptista.com
Then we add some custom variables to easily call it in our serverless functions part:
1custom:2 stage: ${opt:stage, self:provider.stage}3 prefix: ${self:service}-${self:custom.stage}4 web: ${self:custom.prefix}-web5 artisan: ${self:custom.prefix}-artisan
To reduce the size of the file (not much though) we will add some more folders to exclude from the deployment:
1package:2 patterns:3 ...4 - '!docker/**'5 - '!stubs/**'
In our functions part, we add the name of them, so we can identify them quickly when looking at the Lambda in the AWS console, and also update the bref to use php 8.1:
1functions: 2 web: 3 name: ${self:custom.web} 4 ... 5 layers: 6 - ${bref:layer.php-81-fpm} 7 ... 8 9 artisan:10 name: ${self:custom.artisan}11 ...12 layers:13 - ${bref:layer.php-81} # PHP14 - ${bref:layer.console} # The "console" layer
In the last part, we add the bucket deployment plugin:
1plugins:2 - ./vendor/bref/bref3 - serverless-deployment-bucket
Creating S3 bucket
As our deployment files will be in S3, we will need to create the bucket:
Note You must change the command below to suit your AWS information. Also, the bucket must have the same name as you defined in your serverless.yml
.
1aws --profile benjatech s3api create-bucket --bucket maurobaptista.com --region us-east-1
Setting Github Actions
Now we need to add a way to deploy it in AWS Lambda, for that we are going to use Github Actions.
To do that, we need to create the file: .github\workflows\release.yml
with the content:
1name: Release 2 3on: 4 push: 5 branches: 6 - main 7 8env: 9 PROJECT : "maurobaptista.com"10 STAGE : "production"11 AWS_REGION : "us-east-1"12 PHP_VERSION : "8.1"13 COMPOSER_VERSION : "v2"14 15permissions:16 id-token: write17 contents: read18 19jobs:20 deploy-lambda:21 name: Deploy Lambda22 runs-on: ubuntu-latest23 24 steps:25 - name: Checkout26 uses: actions/checkout@v327 28 - name: Configure AWS credentials29 uses: aws-actions/configure-aws-credentials@v130 with:31 role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/${{ env.PROJECT }}-github-action-role32 aws-region: ${{ env.AWS_REGION }}33 role-duration-seconds: 90034 role-session-name: Lambda35 36 - name: Setup PHP37 uses: shivammathur/setup-php@v238 with:39 php-version: ${{ env.PHP_VERSION }}40 tools: composer:${{ env.COMPOSER_VERSION }}41 coverage: none42 43 - name: Get File from Parameter Store44 run: ./deploy/write_to_file.php "$(aws --region ${{ env.AWS_REGION }} ssm get-parameter --with-decryption --name /${{ env.PROJECT }}/${{ env.STAGE }}/env)" .env45 46 - name: Npm install & build47 run: |48 npm install49 npm run build50 51 - name: Install Serverlesss52 run: |53 npm install serverless -g54 npm install serverless-lift -g55 npm install serverless-deployment-bucket -g56 57 - name: Composer install58 run: composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev59 60 - name: Prepare Laravel61 run: |62 php artisan config:clear63 php artisan route:clear64 php artisan view:clear65 touch ./storage/logs/laravel.log66 67 - name: Deploy Lambda68 run: serverless deploy --stage ${{ env.STAGE }}
As you can see above, you need to change some data on the code above. Please, take a look at the env
part and adjust it for your needs.
You will also need to add the AWS_ACCOUNT_ID
to your repository Github Secrets.
Storing our .env in Parameter Store
As we should never commit our .env file, we are going to store it in Parameter Store in AWS. So, our Github Actions will include the .env file in our deployment zip.
Add the .env for production in a file (e.g. .env.prod) and upload it to AWS Parameter Store. Not that the name must be the same as you set in the Github Actions.
1aws --profile benjatech ssm put-parameter --name /maurobaptista.com/production/env --value file://.env.prod --type SecureString
Where the --name
is: --name /{your project name}/{stage}/env
Remember to delete the created file, so you do not commit it.
Creating the .env file to deploy
The Github Actions configuration also calls a php script to create the .env
file from the data in AWS Parameter Store.
1#!/usr/bin/env php 2 3<?php 4 5if (!isset($argv[1])) { 6 echo 'No data set'; 7 return 1; 8} 9 10if (!isset($argv[2])) {11 echo 'No filename set';12 return 1;13}14 15$parameter = json_decode($argv[1], true);16 17if (json_last_error() !== JSON_ERROR_NONE) {18 echo 'Invalid Json';19 return 1;20}21 22if (!isset($parameter['Parameter'])) {23 echo 'No parameters index found';24 return 1;25}26 27file_put_contents($argv[2], $parameter['Parameter']['Value']);28 29return 0;
This is a straightforward code that will get the value you pass to it, and then store it into a file.
Creating an Open ID Connect between AWS and Github
To allow our Github Action to connect with our AWS account, we must create the connection for it:
1aws --profile benjatech iam create-open-id-connect-provider --url https://token.actions.githubusercontent.com --thumbprint-list 6938fd4d98bab03faadb97b34396831e3780aea1 --client-id-list sts.amazonaws.com
If you want to know more: Github Actions update on OIDC-based deployments to AWS
Creating the role that Github Action will assume
As you could see in the action to release, we will make our Github Action assume a role, so we need to create this role.
First, create a JSON file called role.json
with the content:
1{ 2 "Version": "2012-10-17", 3 "Statement": [ 4 { 5 "Effect": "Allow", 6 "Principal": { 7 "Federated": "arn:aws:iam::***:oidc-provider/token.actions.githubusercontent.com" 8 }, 9 "Action": "sts:AssumeRoleWithWebIdentity",10 "Condition": {11 "StringEquals": {12 "token.actions.githubusercontent.com:sub": "repo:maurobaptista/maurobaptista.com:ref:refs/heads/main"13 },14 "ForAllValues:StringEquals": {15 "token.actions.githubusercontent.com:iss": "https://token.actions.githubusercontent.com",16 "token.actions.githubusercontent.com:aud": "sts.amazonaws.com"17 }18 }19 }20 ]21}
Replace the *** with your AWS Account Id, and also on the
token.actions.githubusercontent.com:sub
replace it with your repository.
Now we create the role in AWS using the file as the content:
1aws --profile benjatech iam create-role --role-name maurobaptista.com-github-action-role --assume-role-policy-document file://role.json
Remember to delete the created file, so you do not commit it.
Creating the policy
Let's create the policy.
As we did before, lets create a file called
policy.json` with the content:
1{ 2 "Version": "2012-10-17", 3 "Statement": [ 4 { 5 "Effect": "Allow", 6 "Action": [ 7 "s3:*" 8 ], 9 "Resource": [10 "arn:aws:s3:::maurobaptista.com",11 "arn:aws:s3:::maurobaptista.com/*"12 ]13 },14 {15 "Effect": "Allow",16 "Action": [17 "apigateway:GET",18 "apigateway:HEAD",19 "apigateway:OPTIONS",20 "apigateway:PATCH",21 "apigateway:POST",22 "apigateway:PUT",23 "apigateway:DELETE",24 "apigateway:*"25 ],26 "Resource": "*"27 },28 {29 "Effect": "Allow",30 "Action": [31 "cloudformation:CreateStack",32 "cloudformation:DescribeStacks",33 "cloudformation:DescribeStackEvents",34 "cloudformation:DescribeStackResource",35 "cloudformation:DescribeStackResources",36 "cloudformation:ValidateTemplate",37 "cloudformation:UpdateStack",38 "cloudformation:ListStacks",39 "cloudformation:DeleteChangeSet",40 "cloudformation:CreateChangeSet",41 "cloudformation:DescribeChangeSet",42 "cloudformation:ExecuteChangeSet",43 "cloudformation:ListStackResources",44 "iam:GetRole",45 "iam:AttachRolePolicy",46 "iam:CreateRole",47 "iam:PutRolePolicy",48 "iam:DeleteRolePolicy",49 "iam:TagPolicy",50 "iam:TagRole",51 "lambda:*",52 "logs:*"53 ],54 "Resource": "*"55 },56 {57 "Effect": "Allow",58 "Action": [59 "iam:PassRole"60 ],61 "Resource": [62 "arn:aws:sts::***:assumed-role/maurobaptista.com-github-action-role/*",63 "arn:aws:iam::***:role/maurobaptista-production-us-east-1-lambdaRole"64 ]65 },66 {67 "Effect": "Allow",68 "Action": [69 "ssm:GetParameter"70 ],71 "Resource": [72 "arn:aws:ssm:us-east-1:***:parameter/maurobaptista.com/production/*"73 ]74 }75 ]76}
Replace the *** with your AWS Account Id, on the
s3
replace it with your bucket name, and also on theiam:PassRole
change the first line to have your project name on it, and the second one to have the serverless.yaml service name (first line in the file)
Then we are going to create the policy, remember to take the policy ARN, as we are going to use it next:
1aws --profile benjatech iam create-policy --policy-name maurobaptista.com-github-action-policy --policy-document file://policy.json
Remember to delete the created file, so you do not commit it.
Attaching the policy to the role
Replace the
role-name
with the role name you created, and also replace thepolicy-arn
with the one you just created.
1aws --profile benjatech iam attach-role-policy --role-name maurobaptista.com-github-action-role --policy-arn arn:aws:iam::xxx:policy/maurobaptista.com-github-action-policy
Deploying
After you commit all to your main branch, it will trigger an Action in GitHub. Go to your repository page, and click Actions. There you should see a Deploy Lambda job, then go to the Deploy Lambda step (yes, the name is the same). Then you will find the endpoint to access your deployed app.
Possible Errors
If you face the errors that AWS Cloud Formation is in ROLLBACK_IN_PROGRESS (or ROLLBACK_COMPLETE) go to AWS CloudFormation and manually delete the stack.
Performance
This blog is using the approach above. I believe the results are not perfect, but it is good enough.
More
I also use a similar approach to run Workers in Lambda, if you want to know more: Running Laravel workers in AWS Lambda