Download an already uploaded Lambda function

Amazon Web-ServicesAws Lambda

Amazon Web-Services Problem Overview


I created a lambda function in AWS (Python) using "upload .zip" I lost those files and I need to make some changes, is there is any way to download that .zip?

Amazon Web-Services Solutions


Solution 1 - Amazon Web-Services

Yes!

Navigate over to your lambda function settings and on the top right you will have a button called "Actions". In the drop down menu select "export" and in the popup click "Download deployment package" and the function will download in a .zip file.

Action button on top-right

Step#1

A popup from CTA above (Tap "Download deployment package" here)

Step#2

Solution 2 - Amazon Web-Services

Update: Added link to script by sambhaji-sawant. Fixed Typos, improved answer and script based on comments!

You can use aws-cli to download the zip of any lambda.

First you need to get the URL to the lambda zip $ aws lambda get-function --function-name $functionName --query 'Code.Location'

Then you need to use wget/curl to download the zip from the URL. $ wget -O myfunction.zip URL_from_step_1

Additionally you can list all functions on your AWS account using

$ aws lambda list-functions

I made a simple bash script to parallel download all the lambda functions from your AWS account. You can see it here :)

Note: You will need to setup aws-cli before using the above commands (or any aws-cli command) using aws configure

Full guide here

Solution 3 - Amazon Web-Services

You can use shell script available here

Solution 4 - Amazon Web-Services

If you want to download all the functions in the given region here is my workaround. I have created a simple node script to download function. Install all the required npm packages and set your AWS CLI to the region you want before running the script.

let download = require('download-file');
let extract = require('extract-zip');
let cmd = require('node-cmd');

let downloadFile = async function (dir, filename, url) {
    let options = {
        directory: dir,
        filename: filename
    }
    return new Promise((success, failure) => {
        download(url, options, function (err) {
            if (err) {
                failure(err)
            } else {
                success('done');
            }
        })
    })
}

let extractZip = async function (source, target) {
    return new Promise((success, failure) => {
        extract(source, { dir: target }, function (err) {
            if (err) {
                failure(err)
            } else {
                success('done');
            }
        })
    })
}

let getAllFunctionList = async function () {
    return new Promise((success, failure) => {
        cmd.get(
            'aws lambda list-functions',
            function (err, data, stderr) {
                if (err || stderr) {
                    failure(err || stderr)
                } else {
                    success(data)
                }
            }
        );
    })
}

let getFunctionDescription = async function (name) {
    return new Promise((success, failure) => {
        cmd.get(
            `aws lambda get-function --function-name ${name}`,
            function (err, data, stderr) {
                if (err || stderr) {
                    failure(err || stderr)
                } else {
                    success(data)
                }
            }
        );
    })
}

let init = async function () {
    try {
        let { Functions: getAllFunctionListResult } = JSON.parse(await getAllFunctionList());
        let getFunctionDescriptionResult, downloadFileResult, extractZipResult;
        getAllFunctionListResult.map(async (f) => {
            var { Code: { Location: getFunctionDescriptionResult } } = JSON.parse(await getFunctionDescription(f.FunctionName));
            downloadFileResult = await downloadFile('./functions', `${f.FunctionName}.zip`, getFunctionDescriptionResult)
            extractZipResult = await extractZip(`./functions/${f.FunctionName}.zip`, `/Users/malhar/Desktop/get-lambda-functions/final/${f.FunctionName}`)
            console.log('done', f.FunctionName);
        })
    } catch (e) {
        console.log('error', e);
    }
}


init()

Solution 5 - Amazon Web-Services

You can find a python script to download all the lambda functions here.

import os
import sys
from urllib.request import urlopen
import zipfile
from io import BytesIO

import boto3

def get_lambda_functions_code_url():

client = boto3.client("lambda")

lambda_functions = [n["FunctionName"] for n in client.list_functions()["Functions"]]

functions_code_url = []

for fn_name in lambda_functions:
    fn_code = client.get_function(FunctionName=fn_name)["Code"]
    fn_code["FunctionName"] = fn_name
    functions_code_url.append(fn_code)

return functions_code_url


def download_lambda_function_code(fn_name, fn_code_link, dir_path):

    function_path = os.path.join(dir_path, fn_name)
    if not os.path.exists(function_path):
        os.mkdir(function_path)

    with urlopen(fn_code_link) as lambda_extract:
        with zipfile.ZipFile(BytesIO(lambda_extract.read())) as zfile:
            zfile.extractall(function_path)


if __name__ == "__main__":
    inp = sys.argv[1:]
    print("Destination folder {}".format(inp))
    if inp and os.path.exists(inp[0]):
        dest = os.path.abspath(inp[0])
        fc = get_lambda_functions_code_url()
        print("There are {} lambda functions".format(len(fc)))
        for i, f in enumerate(fc):
            print("Downloading Lambda function {} {}".format(i+1, f["FunctionName"]))
            download_lambda_function_code(f["FunctionName"], f["Location"], dest)
    else:
        print("Destination folder doesn't exist")

Solution 6 - Amazon Web-Services

Here is a bash script that I used, it downloads all the functions in the default region:

download_code () {
    local OUTPUT=$1
    OUTPUT=`sed -e 's/,$//' -e 's/^"//'  -e 's/"$//g'  <<<"$OUTPUT"`
    url=$(aws lambda get-function --function-name get-marvel-movies-from-opensearch --query 'Code.Location' )
    wget $url -O $OUTPUT.zip
}

FUNCTION_LIST=$(aws lambda list-functions --query Functions[*].FunctionName)
for run in $FUNCTION_LIST
do
    download_code $run
done

echo "Finished!!!!"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionElheni MokhlesView Question on Stackoverflow
Solution 1 - Amazon Web-ServicesBubble HackerView Answer on Stackoverflow
Solution 2 - Amazon Web-ServicesArjun NemaniView Answer on Stackoverflow
Solution 3 - Amazon Web-ServicesSambhaji SawantView Answer on Stackoverflow
Solution 4 - Amazon Web-ServicesMayur ShingareView Answer on Stackoverflow
Solution 5 - Amazon Web-ServicesrAmView Answer on Stackoverflow
Solution 6 - Amazon Web-ServiceskumarahulView Answer on Stackoverflow