Skip to content

Instantly share code, notes, and snippets.

@dnmellen
Created January 31, 2017 15:07
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dnmellen/07a0a7935b55a75520631d0fd05d45a5 to your computer and use it in GitHub Desktop.
Save dnmellen/07a0a7935b55a75520631d0fd05d45a5 to your computer and use it in GitHub Desktop.
AWS Lambda function that performs an ssh command through a bastion server to another server. The function will be triggered by a Cloudwatch Alarm
import json
import boto3
import paramiko
def worker_handler(event, context):
ALLOWED_HOSTS = [
'host1',
'host2,
]
ec2 = boto3.resource('ec2')
message = json.loads(event['Records'][0]['Sns']['Message'])
instance_id = [d['value'] for d in message['Trigger']['Dimensions'] if d['name'] == 'InstanceId'][0]
hostname = [t['Value'] for t in ec2.Instance(instance_id).tags if t['Key'] == 'Name'][0]
hostname = hostname.lower().replace('.', '-').strip()
if hostname not in ALLOWED_HOSTS:
print "{} not in ALLOWED_HOSTS. Exiting...".format(hostname)
return {
'message': "Script execution completed. See Cloudwatch logs for complete output"
}
s3_client = boto3.client('s3')
# Download private key file from secure S3 bucket
s3_client.download_file('bucketname', 'certs/key.pem', '/tmp/key.pem')
k = paramiko.RSAKey.from_private_key_file("/tmp/key.pem")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
host = "ec2-user@{}.servers.yourserver.com".format(hostname)
bastion_host = "youradmin.yourserver.com"
print "Connecting to " + bastion_host
c.connect(hostname=bastion_host, username="ec2-user", pkey=k)
print "Connected to " + bastion_host
commands = [
"sudo ssh {} sudo service supervisord restart".format(host)
]
for command in commands:
print "Executing {}".format(command)
stdin, stdout, stderr = c.exec_command(command)
print stdout.read()
print stderr.read()
return {
'message': "Script execution completed. See Cloudwatch logs for complete output"
}
@nimesh7424
Copy link

Unable to import module 'lambda_function': No module named 'paramiko'

@yamatt
Copy link

yamatt commented Oct 28, 2018

@nimesh7424 I expect you'll have to include paramiko in your deployment package

@saifkamaal
Copy link

this can be used to ssh to non-aws provisioned servers as well?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment