Skip to content

Instantly share code, notes, and snippets.

@s9k96
Created July 10, 2020 15:59
Show Gist options
  • Save s9k96/dcc3ec5db6f5e07877d487cb3968a887 to your computer and use it in GitHub Desktop.
Save s9k96/dcc3ec5db6f5e07877d487cb3968a887 to your computer and use it in GitHub Desktop.
Lambda function for starting an already set EC2 instance and ssh-ing into it using Paramiko library.
"""
Lambda function for starting an already set EC2 instance and ssh-ing into it using Paramiko library.
Paramiko is installed on lambda using lambda layers.
"""
import json
import paramiko
import boto3
region = ''
ec2 = boto3.resource('ec2', region_name = region)
s3_client = boto3.client('s3')
def start_instance(id):
ec2 = boto3.client('ec2')
response = ec2.start_instances(InstanceIds=[id], DryRun = False)
return response
def get_ip_from_instance(id):
instance = None
for i in ec2.instances.all():
if i.id == id:
instance = i
print(i)
if instance.state.get('Name')!='running':
print(instance.state.get('Name'))
# print(instance.id)
start_instance(instance.id)
instance.wait_until_running()
instance.load()
return instance.public_ip_address
def lambda_handler(event, context):
# TODO implement
instance_id = '' # Instance id of ec2 instance
ip = get_ip_from_instance(instance_id)
print(ip)
bucket_name = '' # S3 bucket where .pem file is stored
file_name = '' # filename of .pem file
s3_client.download_file(bucket_name, file_name, f'/tmp/{file_name}')
key = paramiko.RSAKey.from_private_key_file(f"/tmp/{file_name}")
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
host=ip
print("Connecting to : " + host)
# connecting to server
ssh_client.connect(hostname=host, username="ubuntu", pkey=key)
print("Connected to :" + host)
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment