-
-
Save jojees/c8330b2e434fa2bfcc8f6fd0fca9f2cc 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment