Skip to content

Instantly share code, notes, and snippets.

@dnmellen
Created January 31, 2017 15:07
Show Gist options
  • Save dnmellen/07a0a7935b55a75520631d0fd05d45a5 to your computer and use it in GitHub Desktop.
Save dnmellen/07a0a7935b55a75520631d0fd05d45a5 to your computer and use it in GitHub Desktop.

Revisions

  1. dnmellen created this gist Jan 31, 2017.
    50 changes: 50 additions & 0 deletions worker_function.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    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"
    }