Run AWS Lambda with PHP

Tram Ho

At the present time (04.04.2020) aws lambda does not support default php programs on their system, only supports languages ​​like python, nodejs … if you want to use php code on lambda they We have to manually build the runtime of php to execute our code. This article I will guide you the steps necessary to run php code on each lambda field.

Build php runtime

Perform the following steps to build custom php runtime.

  1. Initialize EC2 instance amzn-ami-hvm-2018.03.0.20181129-x86_64-gp2 . Note that you must use the aws instance to perform this build runtime, you cannot build locally or any other server, if the build on another environment put into the lambda it will file error.
  2. The SSh enters the newly created ec2 server executing the following commands. Install the necessary packages:
  3. Conducting PHP Compiling
    1. Download PHP 7.3 source
    2. Compiling

    This build operation takes a long time, please wait a bit ? After you have done this, it will create a load of folders in /home/ec2-user/php-7.3-bin/ directory for you, including a php file in the ~/php-7.3-bin/bin/php directory ~/php-7.3-bin/bin/php , this is what you need to run php on each lambda field. Here you can download this ~/php-7.3-bin/bin/php do it locally.

  4. Next step, you create a directory structure as follows:

The file will have the following content:

# composer.json

Finally, hello.php

  1. Go to this directory to install the next content
  2. Install composer, many machines already have, then skip this step
  3. Install dependencies
  4. Create zip file to deploy code

    I explain each of these zip files in detail:

    1. the runtime.zip is the php runtime for lambda to run the php code
    2. vendor.zip is php packages like guzzlehttp, aws-sdk-php, you can add any package for coding here.
    3. hello.zip is your source.

    ==> the runtime and vendor will upload it to the lambda layer’s section, and hellp.zip then pload into the function section.

At this step, if anyone knows how to deploy lambda, they can deploy it themselves, I will guide you to deploy new lambda using aws cli.

  1. You must first create a role for the lambda function AWSLambdaBasicExecutionRole and S3FullAccess policies
  2. Configure AWS CLI tool
  3. Create layers
    1. Custom runtime layer
    2. Layer with vendor

After running each of the above commands it will return you an version arn you save this to create a function:

  1. Create function

    ok to this step, you have finished deploying your fucntion lambda, now you need to log into the aws console to add trigger or perform the corresponding add operation.

    Document

Share the news now

Source : Viblo