5

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Vikramsinh Gaikwad
  • 827
  • 1
  • 9
  • 23

2 Answers2

2

PEM keys are a sensitive resource, so in this case I would suggest putting it into AWS Secrets Manager, and then grant Lambda permissions to retrieve that secret.

Here's official tutorial on how to create secret.

Oleksii Donoha
  • 2,911
  • 10
  • 22
2

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"
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992