CodeBuild - ResourceConflictException issue

I have the following buildspec.yml file which I use to build my application with AWS CodeBuild:

version: 0.2

env:
  variables:
    function_name: ${lambda_function_name}
    alias: ${lambda_alias_name}
    files: ${app_files}

phases:
  build:
    commands:
      # Zipping all files from source stage
      - zip -r index.zip $files
      # Updating the lambda function code
      - aws lambda update-function-code --function-name $function_name --zip-file fileb://index.zip
      # Getting the current version being used by the alias
      - export current_version=$(aws lambda get-alias --function-name $function_name --name $alias | grep FunctionVersion | awk -F'"' '{print $4}')
      # Publishing the new lambda version and storing its version number
      #- sleep 2
      - export target_version=$(aws lambda publish-version --function-name $function_name | grep Version | awk -F'"' '{print $4}')
      # Creating the appspec.json file for CodeDeploy
      - echo '{"Resources":[{"myLambdaFunction":{"Properties":{"Alias":"'${lambda_alias_name}'","CurrentVersion":"'$current_version'","Name":"'$lambda_function_name'","TargetVersion":"'$target_version'"},"Type":"AWS::Lambda::Function"}}],"version":0}' >> appspec.json
      # Deployment without CodeDeploy
      #- aws lambda update-alias --function-name $function_name --name $alias --function-version $version 

The execution returns the following error:

An error occurred (ResourceConflictException) when calling the PublishVersion operation: The operation cannot be performed at this time. An update is in progress for resource: arn:aws:lambda:...

I believe the error comes from the fact that update-function-code isn't ready by the time I call publish-version.

A workaround I found was putting a 2 second sleep in the code, but I don't like this solution since it might take longer or I am wasting money paying for unnecessary sleep time.

How can I update this script in order to publish the Lambda function right after the code update is done?


You can use this script to update the status of lambda function

#!/bin/bash

set -xeuo pipefail
export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin

distribution_id="$1"
function_name="$2"
region="$3"

STATE=$(aws lambda get-function --function-name "$function_name" --region $region --query 'Configuration.LastUpdateStatus' --output text)
while [[ "$STATE" == "InProgress" ]]
do
    echo "sleep 5sec ...."
    sleep 5s
    STATE=$(aws lambda get-function --function-name "$function_name" --region $region --query 'Configuration.LastUpdateStatus' --output text)
    echo $STATE
done

Luckily, I developed the CodeBuild to deploy my function to Lambda@Edge and just finished yesterday.