How to Update AWS Lambda Function to Use the Latest Docker Image
Hemanta Sundaray
Published January 10, 2024
Follow the steps below to update your AWS Lambda function to use the latest Docker image.
Note: This blog post assumes that you have already pushed your Docker image to Amazon ECR.
#1 Retrieve the Digest of the Latest Docker Image
Run the following command to retrieve the digest of the latest image in your Amazon ECR repository:
aws ecr describe-images --repository-name <REPOSITORY_NAME> --query 'imageDetails | sort_by(@, &imagePushedAt)[-1].imageDigest'
In this command:
- imageDetails: This is the key that contains the array of image details.
- sort_by(@, &imagePushedAt): This sorts the imageDetails array based on the imagePushedAt field. The @ symbol represents the current element in the array.
- [-1]: This selects the last element from the sorted array, which is the most recent image.
- .imageDigest: This retrieves the imageDigest field from the selected image detail object.
Running this command will return only the digest of the most recently pushed image in the ECR repository.
Note
The term "digest" in this context specifically refers to the SHA (Secure Hash Algorithm) hash value that uniquely identifies the content of a Docker image.
#2 Update Lambda Function to Use the Latest Docker Image
To update your Lambda function to use the latest Docker image, you need to update your Lambda function's configuration. Follow the steps below:
Retrieve the image URI
Get the URI of the latest Docker image you have pushed to ECR. It will be in the format:
<AWS_ACCOUNT_ID>.dkr.ecr.<REGION>.amazonaws.com/<REPOSITORY_NAME>:latest
Update Lambda function
Use the update-function-code command to update the Lambda function to use the new image:
aws lambda update-function-code --function-name <FUNCTION_NAME> --image-uri <IMAGE_URI>
Replace <IMAGE-URI> with your actual image URI.
Note that after running the above command, it may take a few moments for the changes to propagate
To confirm that your Lambda function is indeed using the most recent image, you can directly retrieve the ResolvedImageUri value from the output of the aws lambda get-function command:
aws lambda get-function --function-name <FUNCTION_NAME> --query 'Code.ResolvedImageUri'
The output will include the digest (SHA-256 hash) of the Docker image. Compare this digest with the digest of the latest Docker image, which you retrieved in step 1. If they match, you can confirm that your Lambda function has been successfully updated.