Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 843
Vikramsinh Gaikwad Avatar asked Apr 28 '20 14:04

Vikramsinh Gaikwad


1 Answers

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"
like image 124
Martin Prikryl Avatar answered Sep 29 '22 04:09

Martin Prikryl