AWS Lambda - Exporting functions

Objective

This exercise will show you the steps for exporting and importing Lambda functions between regions manually. If you want more information click here.

Required knowledge:

  • Basic Use of the AWS CLI
  • Javascript language basics

By the end of this exercise, you will be able to:

  • Export and Import Lambda Cross-Region Functions

Estimated Duration: 30 minutes

Approximate Cost: 1 USD

Execution

Create an AWS Lambda Function

  1. Go to the AWS Lambda console: https://console.aws.amazon.com/lambda.
    For this example, choose the region us-east-1 (Northern Virginia).

  2. In the navigation pane, on the left side of the console, select Functions (Functions).

  3. Choose Create Function (Create Role). create function

    • Select Author from scratch (create from scratch)
    • In Function name (function name) insert multi-region-test-function. In Runtime, choose Node.js 14.x.
    • To create the role, select Create (Create). create function
    • The function will be created and you will be redirected to the console’s function editor. In Function Code (Function Code) Copy and paste the code below:
    exports.handler = async (event) => {
       console.log("chamando função lambda...")
       const response = {
            statusCode: 200,
            body: JSON.stringify('Testando o import e export de funções Lambda!'),
       };
       return response;
    };
    
    • Click Test (test) in the top right corner. A pop-up will appear prompting you to set up a test event. create function
    • Select Create new test event (Create new test event), give it the name eventdata in the field Event name (event name) and click Create (Create)
    • Click again Test. The message Execution result: succeeded should appear. By clicking on details, a payload JSON should appear with the text * Hello from Lambda! *. create function
  4. Your Lambda function was created successfully! We will now export it from the current region for further import into another region.

Export the created Lambda function

  1. Go to the AWS Lambda console: https://console.aws.amazon.com/lambda.
    Remembering that for this example we are using the region for now us-east-1 (Northern Virginia).
  2. In the list of roles, select the role multi-region-test-function created earlier. The Configuration tab will appear.
  3. Click Actions -> Export Function create function
    • A pop-up will open offering two options for download: Download AWS SAM file or Download deployment package.
    • Select Deployment package and wait for the download. Note that the downloaded file is a zip file, but with no extension. After downloading, rename the file with the .zip extension so we can use it later.

Import the Lambda function into the second region

  1. Go to the AWS Lambda console: https://console.aws.amazon.com/lambda.
  2. Select the region in the combo in the upper right corner of the console.
    For this example, I will use the region sa-east-1 - South America (Sao Paulo)
  3. If the function doesn’t exist:
    • Perform steps 1.2 and 3 in item 3 of the section Create an AWS Lambda Function above.
  4. In the list of roles, select the role multi-region-test-function created. The Configuration tab will appear.
    • Under Function Code, click Actions, upload to .zip file. upload
      • You can also import your function through an S3 bucket. For this, select Upload a file from Amazon S3 and enter the URL where the.zip is located.
    • Select the previously downloaded zip file (don’t forget to rename it with the .zip extension) and click Save.
    • (Optional) If you want to test your function, set up the test payload as we did in steps 5.6 and 7 of item 3 in Create a Lambda function above.
  5. Ready! Its Lambda function has been copied from one region to another.

Cleaning up

  1. Delete the lambda functions created in both regions.

Create an AWS Lambda Function

If you already have a Lambda function created, you can skip to the next step at Export the Lambda function

  1. Go to the AWS CloudShell console: https://console.aws.amazon.com/cloudshell/home.
    For this example, choose the region us-east-1 (Northern Virginia). CloudShell is not yet available in all regions.

  2. With the command prompt ready, we need create the role to allow execution access to the Lambda function:

    aws iam create-role --role-name lambda-execution --assume-role-policy-document '{"Version": "2012-10-17","Statement": [{ "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}'
    

    Permission is now required before the function can be executed. To do this, add the policy AWS Lambda Basic Executive Role to the role created above:

    aws iam attach-role-policy --role-name lambda-execution --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
    
  3. We will now create the lambda function via CLI. To do this, run the command below:

    echo "exports.handler = async (event) => {
        console.log('chamando função lambda...', event);
        const response = {
            'statusCode': 200,
            'body': JSON.stringify('Testando o import e export de funções Lambda!'),
        };
        return response;
    };" > index.js
    
  4. The above command created the file index.js containing the source code for our Lambda function. Let’s now package the function into a.zip file so we can register it to the AWS Lambda service for the region in question:

    zip multi-region-test-function index.js
    
  5. We can now register the function through the command below:

    export ACC_ID=$(aws sts get-caller-identity --query Account --output text)
    aws lambda create-function --function-name multi-region-test-function --zip-file fileb://multi-region-test-function.zip --handler index.handler --runtime nodejs14.x --role arn:aws:iam::$ACC_ID:role/lambda-execution
    
    • In Function name (function name) insert multi-region-test-function. In Runtime, choose Node.js 12x.
    • To create the role, select Create (Create). The function will be created and you will be redirected to the console’s function editor.
    • Copy and paste the code below:
    exports.handler = async (event) => {
       console.log("chamando função lambda...")
       const response = {
            statusCode: 200,
            body: JSON.stringify('Testando o import e export de funções Lambda!'),
       };
       return response;
    };
    
  6. (Optional) If the function already exists in the AWS Lambda service, you can update the function source code using the command below:

    aws lambda update-function-code --function-name multi-region-test-function --zip-file fileb://multi-region-test-function.zip
    
  7. Let’s now test the created function. Use the command below to invoke the Lambda function via the command line:

    aws lambda invoke --function-name multi-region-test-function --payload $(echo '{ "key_sample": "value_sample" }' | base64) --log-type Tail --query 'LogResult' --output text out | base64 -d
    

    We have an INFO line containing the console message inside the function along with the payload sent, which indicates that the function was executed successfully.

  8. Ready! Your Lambda function was successfully created via the AWS CLI with CloudShell.

Export the created Lambda function

  1. Go to the AWS CloudShell console: https://console.aws.amazon.com/cloudshell/home.
    For this example, choose the region us-east-1 (Northern Virginia).
  2. (Optional) With the command prompt ready, we will list functions Lambda existing in each region. To do this, use the command below, replacing the region if you want:
    aws lambda list-functions --region sa-east-1
    
  3. In this lab, we already know the name of the function we created earlier. In this way, we will export it and generate a.zip with the source code through the command:
    aws lambda get-function --function-name multi-region-test-function --query 'Code.Location' | xargs wget -O multi-region-test-function-exp.zip
    

    You can extract other metadata from the Lambda function, such as timeout settings or environment variables, for example. For this lab, we focused only on the source code for the simplicity of the lab

  4. Ready. We already have the source code for our function and we can import it into another region.

Import the Lambda function into the second region

We will update an existing role in another region. In this example, we will use the region sa-east-1 (North America - Sao Paulo). If the role does not already exist in this region, perform the steps in the step Create a Lambda function described at the beginning of this lab.

  1. Go to the AWS CloudShell console: https://console.aws.amazon.com/cloudshell/home.
    For this example, choose the region us-east-1 (Northern Virginia).
  2. We will update the function multi-region-test-function in the region sa-east-1 (South America - Sao Paulo). To do this, run the following command:
    aws lambda update-function-code --function-name multi-region-test-function --region sa-east-1 --zip-file fileb://multi-region-test-function-exp.zip
    
  3. Let’s now test the import by calling the function. For this:
    aws lambda invoke --function-name multi-region-test-function --payload $(echo '{ "key_sample": "value_sample" }' | base64) --log-type Tail --query 'LogResult' --region sa-east-1 --output text out | base64 -d
    


    We can validate that the function was updated because the INFO log line now also writes the received payload, which did not happen with the function created at the beginning of this lab.

  4. Ready! Its Lambda function was created in another region.

Cleaning up

  1. Delete the lambda functions created in both regions with the following commands:
    aws lambda delete-function --function-name multi-region-test-function --region us-east-1
    aws lambda delete-function --function-name multi-region-test-function --region sa-east-1
    

Conclusion

With this exercise, it was possible to verify how replication of Lambda functions between AWS regions can be used in DR strategies of type. Backup & Restore and Pilot Light. For strategies for Warm Standby and Active-Active, refer to the practical exercise for deploying lambda functions via CI/CD Pipeline.

Source: AWS Lambda - Developer Guide