Friday, April 1, 2022

[SOLVED] How to connect EC2 using pysftp via AWS Lambda without .pem file or alternate to .pem file

Issue

I want to connect EC2 using pysftp library via AWS Lambda. I use below code to connect.

mysftp = pysftp.Connection(
    host=Constants.MY_HOST_NAME,
    username=Constants.MY_EC2_INSTANCE_USERNAME,
    private_key="./clientiot.pem",
    cnopts=cnopts,
)

I have put .pem file along with deployment package in AWS Lambda. See this image:

pem file with deployment package

Sometimes it works sometime not, like sometimes it says .pem file not found.

"[Errno 2] No such file or directory: './clientiot.pem'"

How to deal with it? Is there any way to access .pem file or data of .pem file securely.

I don't want .pem in AWS lambda.


Solution

If you use Paramiko directly (pysftp is just a thin wrapper around Paramiko), you can hard-code the key into your code and you won't have troubles with external resources:
SSH/SCP through Paramiko with key in string


For referring to files in your Lambda task, see:
AWS Lambda read contents of file in zip uploaded as source code

So this should work:

private_key = os.environ['LAMBDA_TASK_ROOT'] + "/clientiot.pem"


Answered By - Martin Prikryl
Answer Checked By - Gilberto Lyons (WPSolving Admin)