'AWS Lambda: cannot import name 'asn1'

I am using pysftp to connect to a sFTP site from a python function. This is working fine from my local that is running as file_track.py. But when I deploy that on AWS lambda it is failing with –

{
  "error Message": "Unable to import module 'lambda function': cannot import name 'asn1' from 'cryptography.hazmat.bindings._rust' (unknown location)",
  "error Type": "Runtime.ImportModuleError",
  "requestId": "0235edb8-25a3-4570-a1ea-2a2696a7dd04",
  "stack Trace": []
}

Please help me out!



Solution 1:[1]

I experienced this error even after following the AWS guide on how to compile lambda functions with extra dependencies. After getting stuck for hours, it turns out to be a difference in the CPU architecture between my personal laptop and the lambda function's runtime environment. My personal laptop is an Asus TUF A15 which is using an x64 AMD Ryzen 7 4800H CPU. However, my Lambda function's runtime was Python 3.8 on x86_64 which is an Intel CPU. The cryptography library packages I was downloading and packaging on my AMD CPU are not compatible with the Intel CPU. Most other libraries work fine though but apparently not the cryptography library.

Solution:

I launched a temporary m5.large EC2 instance running x86_64 AMI for Amazon Linux 2022 (can be a T2, I don't think it matters as long as it's x86_64), then followed the same steps specified on this doc and my function executed successfully without any issues.

Solution 2:[2]

I seems that you have not packed your pysftp python package with your lambda function hence it is unable to find the bindings you can try forming layers this is a similar type of issue that might help you

pysftp library not working in AWS lambda layer

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tino1b2be
Solution 2 priyanshu kumar