Nikhil K Murali
Nikhil K Murali

Reputation: 151

How to ssh into EC2 instance from lambda function

I'm trying to write my first Python code in Lambda function that will check whether i'm able to SSH (port 22) in to an EC2 instance.

I have created an EC2 instance with Security Group 22 CidrIP my public IP then, created a Lambda function with python 3.8 as runtime in the same account

Now, through code i,m trying to SSH into EC2 by passing EC2 Public IP, Username, Key pair

and execute one command, example: sudo su

Question:

  1. Where should i place my keypair?
  2. What is the code to SSH in to EC2 from lambda funtion?

Upvotes: 3

Views: 7108

Answers (1)

jarmod
jarmod

Reputation: 78842

The first thing I would say is that you should almost never SSH from Lambda into EC2. There are much better ways to remotely run scripts on EC2, including:

  1. SSM Run Manager
  2. Expose an API on the EC2 instance and call that API

If you really want to do this, perhaps for some academic reason, then:

  1. store the keypair in Secrets Manager and give the Lambda permission to read it
  2. use a Python package such as Fabric or Paramiko

[Update: it seems that you're trying to validate that SSH access is blocked]

The best way to validate security groups is to use the EC2 API, describe the instance(s), enumerate the security groups and their inbound rules. If you don't trust that approach then you could try to SSH to the instance using the method I proposed above (though you only need to try to connect for the test to be useful, presumably).

The problem you're going to have is that the security groups could potentially have been set up to block all SSH access (which is the default, by the way) with the exception of a single 'attacker' IP address which is allowed. Your Lambda SSH connection attempt will fail, because it's not coming from that one 'attacker' IP, yet your Lambda test will report "I cannot access the web server over SSH, test is successful". That's an invalid test.

Upvotes: 6

Related Questions