SSH into EC2 using lambda function (Paramiko Lib)


I want to establish an SSH connection to an EC2 instance through a Lambda function using the Paramiko library. I have created a Paramiko library layer and attached it to the function. However, when I use the function "key = paramiko.RSAKey.from_private_key_file('EC2-Key.pem')", I encounter an attribute error. This function works perfectly when I run it locally in VSCode. The key file is stored in the same folder as the code. The version of the Paramiko library is the same both locally and in the Lambda layer.

Error: "errorMessage": "module 'paramiko' has no attribute 'RSAKey'", "errorType": "AttributeError", "stackTrace": [ " File "/var/task/", line 40, in lambda_handler\n key = paramiko.RSAKey.from_private_key_file(EC2-Key.pem)\n"

asked a year ago914 views
1 Answer

What about using Amazon Linux2 to create layers?
As noted in the following documentation, it may not work well if created on a local Windows or Mac machine.

The first step to creating a layer is to bundle all of your layer content into a .zip file archive. Because Lambda functions run on Amazon Linux, your layer content must be able to compile and build in a Linux environment. If you build packages on your local Windows or Mac machine, you’ll get output binaries for that operating system by default. These binaries may not work properly when you upload them to Lambda.

The following blogs may be helpful.

profile picture
answered a year ago
  • I am using Ubuntu and have created a layer on it. I have installed the library both locally and in a separate folder. Additionally, I compressed it into a zip file and created a layer. The library works fine locally but in lambda function it gives attribute error.

  • Try to create it using Amazon Linux2 or similar instead of Ubuntu.

  • I did it using Amazon Linux2 but still getting the same error. I have double checked the file and the code for "key = paramiko.RSAKey.from_private_key_file('EC2-Key.pem')", is present but somehow it cannot be accessed in the lambda function.

    Lambda Function have full access of EC2, S3, right now I am testing it that why I have given full access

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions