def upload_external_library_for_lambda_layer()

in lib/lambda_util.py [0:0]


def upload_external_library_for_lambda_layer(url, bucket, language):
  # Determine the key
  file_name = url[url.rindex('/')+1:]
  
  # Key will replace existing extension with zip
  zip_key = file_name.replace(".tar.gz","") + ".zip"

  # If this key is already in our bucket then just return the key and version
  try: 
    header = s3.head_object(Bucket=bucket, Key=zip_key)
    print("Library '{}' already exists, skipping download and sync".format(zip_key))
    return zip_key
  except ClientError as e:
    if e.response['Error']['Code'] == "404": None # If the file isn't found then proceed with the upload
    else: raise
  
  # Determine working directory
  wd = os.getcwd()
  
  # Create temporary directory and move to it
  td = tempfile.mkdtemp()
  os.chdir(td)
  
  # Download the file
  print ("Downloading file '{}' as '{}'".format(url, file_name))
  urllib.request.urlretrieve(url, file_name)
  
  # ----------- Process to make Lambda Layer friendly
  # Untar 
  tar = tarfile.open(file_name)
  tar.extractall()
  tar.close()  
  
  # Rename top folder to work as Lambda Layer
  lib_folder = file_name.replace(".tar.gz","")

  if language == 'python':
    os.rename(lib_folder, language) # Top folder for Lambda Layer expects 'python'
  
  # ----------- Zip and upload
  __zip_folder(zip_key, language)
  __upload_file(zip_key, bucket)

  # Go back to initial working directory
  os.chdir(wd)
  
  # Delete the temporary directory and contents
  shutil.rmtree(td)
  
  return zip_key