Issue
Context: I am trying to use the paramiko Python library to SSH into an EC2 instance from within an AWS Lambda function (written with Python 3.7). The EC2 instance in question exists in a VPC. I know the public IP of this EC2 as well. I have already created a lambda layers package for Paramiko and am able to use the import paramiko
statement with no errors so I know the library works fine.
Attempted Solution: I have utilized this tutorial to try to SSH into the EC2 mentioned above. The code I have thus far is as follows (some information has been randomized for privacy):
import json
import boto3
import paramiko
def lambda_handler(event, context):
s3_client = boto3.client("s3") # Boto3 is the AWS SDK for Python and allows us to manage these 2 services (among other things)
s3_client.download_file("censored-bucket-name", "keyname.pem", "/tmp/keyname.pem")
ssh_key = paramiko.RSAKey.from_private_key_file("/tmp/keyname.pem") # obj type = PKey
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # setting policy to connect to unknown host and trust it
ssh_client.connect(hostname="3.81.62.55", username="ubuntu", pkey=ssh_key) # connecting to ec2 server
return {
statusCode': 200,
body': json.dumps('Commands have been successfully executed ')
}
Issue:
My problem is that upon running this code in Lambda (using an empty test event of "{}"), the code just times out (2 mins) and throws no errors at all.
I can't seem to connect to the EC2 even though my Lambda function is part of the same VPC, uses the same subnets, and has the necessary security groups applied.
Any ideas what I'm doing wrong?
Solution
3.81.62.55
is a public IP. You must use your instance private IP or default EC2 dns url provided by the aws for the instance.
Answered By - Marcin Answer Checked By - Senaida (WPSolving Volunteer)