0

I have a S3 bucket and we are using as code repository to store our Lambda code, which is then read by lambda.

The S3 bucket is version so that every time we upload the script again( after altering the code) there is a new version of the zip file created for the existing file.

Now I want Lambda to automatically pickup the latest version of the zip file automatically instead of me altering it manually in the CloudFormation templet and running it OR attaching it manually to the Lambda every time.

Naman
  • 296
  • 1
  • 10

2 Answers2

2

I was able to resolve the issue ,so just wanted to post the solution for reference:

Followed the below steps:

  1. Make sure that the name of the Lambda function and the name of the zip file ( deployment package) is exactly the same.

  2. Create a Lambda that will be triggered when you upload any new code in your S3 bucket.

  3. Process the event information and use s3 API it to fetch the latest version of the file from s3.

  4. Use boto3 API to reconfigure your final Lambda

    import boto3
    import json
    
    client = boto3.client("s3")
    lambda_client = boto3.client("lambda")
    
    def lambda_handler(event, context):
    
      bucket = event["Records"][0]["s3"]["bucket"]["name"]
      file = event["Records"][0]["s3"]["object"]["key"]
    
      get_version = client.get_object(
                 Bucket = bucket,
                 Key = file
                 )
    
      versionId = (get_version["VersionId"]) #Getting the latest version of the code 
    
      update_lambda = lambda_client.update_function_code(
                         FunctionName= file.split("/")[-1].split(".")[0],
                         S3Bucket=bucket,
                         S3Key=file,
                         S3ObjectVersion= versionId
                         )
    
Naman
  • 296
  • 1
  • 10
1

If you want to deploy a new version of a Lambda function's code automatically as it is uploaded to the S3 bucket, then you can use S3 Event Notifications to e.g. notify an SNS topic and subscribe another Lambda function which performs the deployment (such as via CloudFormation or AWS SDK deploy lambda function).

httpdigest
  • 5,411
  • 2
  • 14
  • 28
  • Hey Kai, Thanks for the suggestion but I do not want to create a a new lambda but just want to attach the new code.zip version to the existing Lambda's and as there are bunch of then I am afraid the above process will not work with my use case. – Naman Mar 11 '21 at 13:28